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?
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
-NoExit
switch to always leave the PowerShell Console window open after the script finishes running (see registry keys below).Registry key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
.ps1
file and choose Open With -> Windows PowerShell."C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
Registry key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
.ps1
file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed)."C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
Note: The registry keys to update may change in future versions of Windows, but this shows you the basic idea.
See my blog for more information and a script to download that will make the registry change for you.