Sunday, January 18, 2015

Double click file to run a PowerShell script

Typically, you cannot double click on a PowerShell script (.ps1 file) and have it automatically run, like you could with a batch file (.bat or .cmd). This is a good thing because someone may accidentally run something that was not meant to be run.

But what if you need to have someone run a PowerShell script and you just want them to double click a shortcut of some sort to make it happen.

The trick is to create a batch file that invokes the PowerShell. If you give the batch file and PowerShell script the same base name, then the batch file content doesn't have to change:

@echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"

So, for instance, if you wish to run a PowerShell script called xyz.ps1, just create xyz.bat with the above content.

That's it!

By the way, the two pushd/popds are necessary in case the user's CDs is on a different drive. Without the outer set, the CD on the drive with the script will get lost.

No comments: