Table of Contents
In some cases, you want to run a PowerShell script from the command line from anywhere without navigate to the path of the script. By default, when start a new PowerShell session, it starts in the current user folder.
But the script is saved in D:\my scripts folder. When typing the path of the script, it won’t work because the path has a space in it.
If you cover the path with quotes, PowerShell thinks that it is a string and print it to screen instead of executing it.
If the path of the script does not contain any space, the script can be run normally.
To run the script without navigate to the script’s directory. You can try some methods below:
Dot-Sourcing in PowerShell
Dot-sourcing is a concept in PowerShell that allows you to reference code defined in one script in a separate one. This is useful when you’re working on a project with multiple scripts and might have functions specified in one script(s) and the code to call those functions in another.
. "D:\my scripts\test.ps1"
You can run another script from a script as well.
The call operator &
Alternatively, the PowerShell call operator (&) lets you run commands that are stored in variables and represented by strings or script blocks. You can use this to run any native command or PowerShell command. This is useful in a script when you need to dynamically construct the command-line parameters for a native command.
& "D:\my scripts\test.ps1"
The -File parameter
The third way, 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 -ExecutionPolicy Bypass -File "D:\my scripts\test.ps1"
The -Command parameter
The fourth way, if you use the -Command parameter, instead of -File, the -Command content is processed by PowerShell.
powershell.exe -ExecutionPolicy Bypass -Command "& 'D:\my scripts\test.ps1'"
The double quotes are processed by the command line, and & ‘D:\my scripts\test.ps1 is a command that is actually processed by PowerShell.
The -Command is also the default parameter that is used, if you do not specify any.
powershell.exe "& 'D:\my scripts\test.ps1'"
The -EncodedCommand parameter
And the last way, 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 = "& 'D:\my scripts\test.ps1'"
[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($command))
And then you can use the the -EncodedCommand parameter like this:
powershell.exe -EncodedCommand JgAgACcARAA6AFwAbQB5ACAAcwBjAHIAaQBwAHQAcwBcAHQAZQBzAHQALgBwAHMAMQAnAA==
Not a reader? Watch this related video tutorial: