Call a Powershell script from c# code

PowerShell logo This solution given here :
executing-powershell-scripts-from-c is fine, but only works with .NET 4.0 or above…

In my case, I needed to call a powershell script from a c# code source running under .NET 3.5.

So, this is a function that uses a Process objet to run Powershell :


public static int RunPowershellScript(string ps)
{
int errorLevel;
ProcessStartInfo processInfo;
Process process;

processInfo = new ProcessStartInfo("powershell.exe", "-File " + ps);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;

process = Process.Start(processInfo);
process.WaitForExit();

errorLevel = process.ExitCode;
process.Close();

return errorLevel;
}

This code is synchronous, and has a lack of prerequisites checks, but it can be reusable in a more elegant code 😉