How can I run a PowerShell script with white spaces in the path from the command line?

The -File parameter

If you want to run powershell.exe -File from the command line, you always have to set paths with spaces in double quotes ("). Single quotes (') are only recognized by PowerShell. But as powershell.exe is invoked (and hence the file parameter processed) by the command line, you have to use ".

powershell.exe -File "C:\Users\test\Documents\Test Space\test.ps1" -ExecutionPolicy Bypass

The -Command parameter

If you use the -Command parameter, instead of -File, the -Command content is processed by PowerShell. Hence you can – and in this case have to – use ' inside ".

powershell.exe -Command "& 'C:\Users\test\Documents\Test Space\test.ps1'" -ExecutionPolicy Bypass

The double quotes are processed by the command line, and & 'C:\Users\test\Documents\Test Space\test.ps1' is a command that is actually processed by PowerShell.

Solution 1 is obviously simpler.

Note that -Command is also the default parameter that is used, if you do not specify any.

powershell.exe "& 'C:\Users\test\Documents\Test Space\test.ps1'" -ExecutionPolicy Bypass

This would work, too.

The -EncodedCommand parameter

You can encode your command as Base64. This solves many “quoting” issues and is sometimes (but not in your case though) the only possible way.

First you have to create the encoded command

$Command = "& 'C:\Users\test\Documents\Test Space\test.ps1'"
[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Command))

And then you can use the the -EncodedCommand parameter like this

powershell.exe -EncodedCommand JgAgACcAQwA6AFwAVQBzAGUAcgBzAFwAdABlAHMAdABcAEQAbwBjAHUAbQBlAG4AdABzAFwAVABlAHMAdAAgAFMAcABhAGMAZQBcAHQAZQBzAHQALgBwAHMAMQAnAA== -ExecutionPolicy Bypass

Leave a Comment

tech