Archive

Posts Tagged ‘Windows Explorer’

Keep PowerShell Console Window Open After Script Finishes Running

July 7th, 2014 4 comments

I originally included this as a small bonus section at the end of my other post about fixing the issue of not being able to run a PowerShell script whose path contains a space, but thought this deserved its own dedicated post.

When running a script by double-clicking it, or by right-clicking it and choosing Run With PowerShell or Open With Windows PowerShell, if the script completes very quickly the user will see the PowerShell console appear very briefly and then disappear.  If the script gives output that the user wants to see, or if it throws an error, the user won’t have time to read the text.  We have 3 solutions to fix this so that the PowerShell console stays open after the script has finished running:

1. One-time solution

Open a PowerShell console and manually run the script from the command line. I show how to do this a bit in this post, as the PowerShell syntax to run a script from the command-line is not straight-forward if you’ve never done it before.

The other way is to launch the PowerShell process from the Run box (Windows Key + R) or command prompt using the -NoExit switch and passing in the path to the PowerShell file.
For example: PowerShell -NoExit “C:\SomeFolder\MyPowerShellScript.ps1”

2. Per-script solution

Add a line like this to the end of your script:

Read-Host -Prompt “Press Enter to exit”

I typically use this following bit of code instead so that it only prompts for input when running from the PowerShell Console, and not from the PS ISE or other PS script editors (as they typically have a persistent console window integrated into the IDE).  Use whatever you prefer.

# 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
}

I typically use this approach for scripts that other people might end up running; if it’s a script that only I will ever be running, I rely on the global solution below.

3. Global solution

Adjust the registry keys used to run a PowerShell script to include the –NoExit switch to prevent the console window from closing.  Here are the two registry keys we will target, along with their default value, and the value we want them to have:

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\""

The Desired Values add the –NoExit switch, as well wrap the %1 in double quotes to allow the script to still run even if it’s path contains spaces.

If you want to open the registry and manually make the change you can, or here is the registry script that we can run to make the change automatically for us:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit \"& \\\"%1\\\"\""

[HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit \"-Command\" \"if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \\\"%1\\\"\""

You can copy and paste the text into a file with a .reg extension, or just

Simply double-click the .reg file and click OK on the prompt to have the registry keys updated.  Now by default when you run a PowerShell script from File Explorer (i.e. Windows Explorer), the console window will stay open even after the script is finished executing.  From there you can just type exit and hit enter to close the window, or use the mouse to click the window’s X in the top right corner.

If I have missed other common registry keys or any other information, please leave a comment to let me know.  I hope you find this useful.

Happy coding!

Fix Problem Where Windows PowerShell Cannot Run Script Whose Path Contains Spaces

May 28th, 2013 4 comments

Most people will likely find the “Run script path with spaces from File Explorer” (to be able to double click a PS script whose path contains spaces to run it) section below the most helpful.  Most of the other content in this post can be found elsewhere, but I provide it for context and completeness.

 

Make running (instead of editing) the default PowerShell script action

The default Windows action when you double click on a PowerShell script is to open it in an editor, rather than to actually run the script.  If this bugs you, it’s easy enough to fix.  Just right-click on the script, go to “Open with” –> “Choose default program…”, and then select Windows PowerShell, making sure the “Use this app for all .ps1 files” option is checked (this might be called “Always use the selected program to open this kind of file” or something else depending on which version of Windows you are using).

ChooseDefaultPowerShellApplication     MakeWindowsPowerShellDefaultApplication

If you don’t mind opening in an editor as the default action, then to run the script you can just right-click on the script and choose “Open with” –> “Windows PowerShell”.  This is probably how 90% of people run their PowerShell scripts; power uses might run their scripts directly from the PowerShell command prompt.

 

Error message when trying to run a script whose path contains spaces

So the problem that the 90% of people are likely to encounter is that as soon as the script path has a space in it (either in the filename itself or in the directory path the file resides in), they will see the powershell console flash some red text at them for about 1/10th of a second before it closes, and they will be wondering why the script did not run; or worse, they won’t know that it didn’t run (see the “Keep PowerShell Console Open” section below).  If they are lucky enough to press Print Screen at the right moment, or decide to open up a PowerShell console and run from there, they might see an error message similar to this:

Powershell Invalid Path Error Message

“The term ‘C:\My’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.”

So the path to the script I was trying to run is "C:\My Folder\My PowerShell Script.ps1", but from the error you can see that it cut the path off at the first space.

 

Run script path with spaces from PowerShell console

So the typical work around for this is to open a PowerShell console and run the script by enclosing the path in double quotes.

Windows 8 Pro Tip: You can open the PowerShell console at your current directory in File Explorer by choosing File –> Open Windows PowerShell.

Open Powershell From File Explorer

If you simply try to run the script by enclosing the path to the script in double quotes you will just see the path spit back at you in the console, instead of actually running the script.

Try to run script with spaces the wrong way

The trick is that you have to put “& “ before the script path to actually run the script.  Also, if you are trying to run a script from the current directory without using the full path, you will need to put “.\” before the relative script filename.

Run PowerShell script the right way

 

Run script path with spaces from File Explorer

So when we are in the PowerShell console we can manually type the path enclosed in double quotes, but what do we do when simply trying to run the file from File Explorer (i.e. Windows Explorer in Windows 7 and previous) by double clicking it? 

The answer: Edit the registry to pass the file path to powershell.exe with the path enclosed in quotes.

The problem is that the “HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command” registry key value looks like this:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"

but we want it to look like this:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""

 

So if you want to go manually edit that key by hand you can, or you can simply download the registry script below and then double click the .reg file to have it update the registry key value for you (choose Yes when asked if you want to continue).

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" \"& \\\"%1\\\"\""

IMHO this seems like a bug with the PowerShell installer (and Windows since PowerShell is built into Windows 7 and up), so please go up-vote the bug I submitted to get this fixed.

So now you can run your PowerShell scripts from File Explorer regardless of whether their path contains spaces or not Smile.  For those interested, this is the post that got me thinking about using the registry to fix this problem.

 

Bonus: Keep PowerShell console open when script is ran from File Explorer

Update – This Bonus section now has its own updated dedicated post here that you should use instead.

When running a script by double-clicking it, if the script completes very quickly the user will see the PowerShell console appear very briefly and then disappear.  If the script gives output that the user wants to see, or if it throws an error, the user won’t have time to read the text.  The typical work around is to open the PowerShell console and manually run the script.  The other option is to adjust our new registry key value a bit.

So to keep the PowerShell console window open after the script completes, we just need to change our new key value to use the –NoExit switch:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" –NoExit "& \"%1\""

And here is the .reg script with the –NoExit switch included:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit \"& \\\"%1\\\"\""

I hope you find this information as useful as I did.  Happy coding!