Jeroen Swart

.NET Architect

Executing powershell scripts

I'm using powershell a lot for performing upgrade actions on an existing Sharepoint installation. I try to keep the manual tasks to a minimum, since the (exact) same actions must be executed on different environments (DTAP).

Powershell scripts won't execute like a command file (like double-clicking in the explorer). Instead you need to open a commandline, navigate to the correct folder, start the powershell environment and then you can execute the powershell script. This is not so much an issue when a whole set of scripts need to be executed, but when I just want to run a single script this feels like a lot of work just to start a single script. So to make executing a powershell script a little easier, I've created a simple command file that will execute a single script. It works simply by dropping the desired powershell script on it in the explorer.

Create a command file with a name like 'ExecutePowershell.cmd' and put in the following code:

@echo off.
echo Execute powershell:
echo %1%

powershell.exe "& "%1%""
@echo on

The trick here is of course in the way powershell is started. You can use this syntax to run scripts from a file, like so:

powershell "& .\scriptfile.ps1"

Don't forget the .\ if you're running a script from the current directory (or powershell won't find the script). And when the path to the script contains spaces, place it between double double quotes (because the quotes are used within an, already quoted, string), like so:

powershell "& ""Installation Scripts\scriptfile.ps1"""

Or run a single (or several) statements, like so:

powershell "& get-process"

Comments are closed