Flattr this Bookmark and Share

Tuesday, January 15, 2013

Run PowerShell from .NET program without System.Management.Automation

I have run into the problem a couple of times where it's not "easy" to add a reference to System.Management.Automation in order to execute PowerShell scripts from .NET code.  I found a way around it which works for simple scenarios where you might just want to execute some script and read the standard output plus error output.

System.Management.Automation can be an issue because you may need to install a Windows SDK in order to get the DLL on your machine (http://stackoverflow.com/a/1187978/281177).  Then there can be versioning issues also.  One workaround seems to be to hack the csproj file to just reference it and hope that Visual Studio knows what to do, for example this solution: http://stackoverflow.com/a/1372061/281177.

Here is some sample code on how to execute a PowerShell script and get the error plus standard output from it using System.Management.Automation:
An alternative is to write some simple code that just executes a batch file, where the batch file kicks off running PowerShell, and take one argument which is the batch file to run:
The batch file can either run the default PowerShell detected:
Or you could try and force it to use a particular "powershell.exe" version by specifying a full path:


DISCLAIMER: I only tested this on a very simple scenario and it was a quick way around the problem.  I would be interested to know if you end up using this scenario how it goes for you.  Please leave a comment!