active-directorypowershell-2.0

How to keep the shell window open after running a PowerShell script?


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?


Solution

  • You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.

    1. 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"
    2. Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
    3. Global Fix: Change your registry key by adding the -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

    Registry key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command

    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.