How to run PowerShell scripts directly from Windows command line
If you find yourself in the regular command line (cmd.exe
) on Windows and you'd like to run a PowerShell script, you can do it like this:
powershell ./example-script.ps1
Would be nice if you could just run it directly as a bat file though, right? And yes, you can!
Simply open up an elevated command prompt and then run the following commands:
setx PATHEXT "%PATHEXT%;.PS1" /m
assoc .ps1=Microsoft.PowerShellScript.1
ftype Microsoft.PowerShellScript.1="%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "%1"
This tells Windows that files with the .ps1 file extension should be considered executable, that their file type should be Microsoft.PowerShellScript.1
and that this file type should be sent as a parameter to the PowerShell executable.
You might want to check if there is something registered for this file type already before you do this. To do that simply run assoc .ps1
and ftype Microsoft.PowerShellScript.1
. For me the file type was already associated with ps1 files, but the handler was set to notepad for some reason.
Either way, after opening up a new command prompt (to make sure the new PATHEXT
environment variable is loaded), you should be able to run PowerShell scripts directly just like .bat
and .exe
files:
example-script
Yey!
...ExecutionPolicy?
When trying to run your own scripts, you might also be blocked by a restricted execution policy. If so, open up a powershell console and run the following:
Set-ExecutionPolicy RemoteSigned