【发布时间】:2013-05-20 07:29:10
【问题描述】:
我有一个非常短的 PowerShell 脚本,它连接到服务器并导入 AD 模块。我想通过双击运行脚本,但恐怕窗口会在最后一行之后立即关闭。
我该如何解决这个问题?
【问题讨论】:
标签: active-directory powershell-2.0
我有一个非常短的 PowerShell 脚本,它连接到服务器并导入 AD 模块。我想通过双击运行脚本,但恐怕窗口会在最后一行之后立即关闭。
我该如何解决这个问题?
【问题讨论】:
标签: active-directory powershell-2.0
您基本上有 3 个选项来阻止 PowerShell 控制台窗口关闭,我描述了 in more detail on my blog post。
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
-NoExit 开关来更改您的注册表项,以便在脚本完成运行后始终保持 PowerShell 控制台窗口打开。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 { <The script to actually run> } 包装您的脚本 使用户能够通过 UI 启动脚本并查看结果而无需编辑注册表项
错误... 我应该知道的:
powershell -noexit <path\script>
仅此而已:)
【讨论】:
以下解决方案在运行 Powershell ISE 时阻止脚本关闭,否则允许脚本关闭。
# 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
}
【讨论】:
在我自己的情况下,我想将 powershell 添加到 Windows 7 上的上下文菜单中。即右键单击文件夹或文件夹内以获取菜单以启动 Powershell 窗口,而不会在启动后关闭它。这里的答案帮助我做到了这一点,我想在这里分享它,以防它帮助其他人。
要使右键单击在文件夹内工作,这意味着右键单击文件夹内的空白区域,请重复这些步骤,但这一次,注册表位置是:
HKEY_CLASSES_ROOT\Directory\shell
命令是:
C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell .exe -noexit
在 Windows 7 Ultimate sp1 上测试过,但我想我可能也适用于更高版本的 Windows
【讨论】:
只需在脚本底部的新行添加暂停,就像在批处理文件中一样。
【讨论】:
如果您只想让窗口保持打开状态,可以在脚本末尾添加pause,或者如果您希望之后能够运行命令,可以添加powershell(显然不要执行第二个如果其他人将使用您的代码,则可以选择)。
【讨论】: