我有一个非常简短的PowerShell脚本,它连接到服务器并导入AD模块。我希望通过双击运行该脚本,但我担心在最后一行之后窗口立即关闭。
如何解决这个问题?
如何解决这个问题?
你基本上有三个选项来防止PowerShell控制台窗口关闭,我在我的博客文章中更详细地描述了它们。
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "按Enter键退出"
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Description: Key used when you right-click a .ps1 file and choose Open With -> Windows PowerShell.
Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Description: Key used when you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
请查看我的博客获取更多信息,并下载一个脚本,它将帮助您进行注册表更改。
powershell -NoExit -Command { <要实际运行的脚本> }
包装起来。
使用户能够通过UI启动脚本并查看结果,而无需编辑注册表键。 - SchreiberLex-NoExit
参数的 PowerShell 窗口(而不是 cmd),并运行 SomeScript.ps1? - xr280xrstart
是我需要的。创建了一个批处理文件,其中包含 start PowerShell -NoExit -File "[.ps1 脚本路径]"
。如果没有 start
,它会在 Windows 命令提示符中运行 PowerShell。 - xr280xr呃...... 我本应该知道的:
powershell -noexit <path\script>
就是这样了 :)
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
如果你只想让窗口保持打开状态,可以在脚本末尾添加pause
;如果你想要在之后运行命令,可以添加powershell
(如果其他人也会使用你的代码,显然不要选择第二个选项)。
要使右键单击文件夹内的空白处起作用,请重复步骤,但是此时注册表位置为:
HKEY_CLASSES_ROOT\Directory\shell
命令为:
C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell.exe -noexit
在 Windows 7 Ultimate SP1 上测试过,但我认为它对于较新版本的 Windows 也可能适用。