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?
PowerShell NoExit switch prevents the PowerShell console window from closing after running the script. When you double click on the PowerShell script file, or run with the PowerShell option, the script will execute quickly and then disappear.
So, let's check out how you can disable the PowerShell Startup status on the Task Manager: Press Ctrl + Shift + Esc to open the Task Manager. Navigate to the Startup tab. Right-click on the Windows PowerShell option and select Disable.
The Start-Job cmdlet starts a PowerShell background job on the local computer. A PowerShell background job runs a command without interacting with the current session. When you start a background job, a job object returns immediately, even if the job takes an extended time to finish.
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.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\""
See my blog for more information and a script to download that will make the registry change for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With