问题
I have a very short PowerShell script that connects to a server and imports the AD module. I'd like to run the script simply by double clicking, but I'm afraid the window immediately closes after the last line.
How can I sort this out?
回答1:
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
- One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1" - Per-script Fix: Add a prompt for input to the end of your script file. e.g.
Read-Host -Prompt "Press Enter to exit" - Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running.
See my blog for more information on which registry keys to modify.
回答2:
Errr... I should have known:
powershell -noexit <path\script>
and that's all there's to it :)
回答3:
The solution below prevents the script from closing when running Powershell ISE and allows the script to close otherwise.
# 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
}
来源:https://stackoverflow.com/questions/16739322/how-to-keep-the-shell-window-open-after-running-a-powershell-script