PowerShell Tip #10 - Read ExitCode from C# for a PowerShell script

by rahul 12/26/2012 11:56:26 AM

The requirement is that you need to set an ExitCode in your PowerShell script and act appropriately in C# code. Sounds quite simple initially, but it is a little bit tricky. Here is how to achieve this.

Part 1: Modify your PowerShell code

    Your PowerShell Code here

$host.SetShouldExit(100) #Set the Exitcode here. I am setting it to 100 } catch [System.Exception] { AddToLog("$_") #Add to log or whatever you feel like }

Part 2: Read the exit code in C#

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "powershell";
psi.WorkingDirectory = Environment.CurrentDirectory + "\\Scripts";
psi.Arguments = Environment.CurrentDirectory + "\\Scripts\\ScriptFile.ps1";
psi.WindowStyle = ProcessWindowStyle.Maximized;
Process p = Process.Start(psi);
if (p.ExitCode == 100)
     // Do something for Success
     // Do something for failure


Hope this helps, Wave


Quote of the day:
"Three may keep a secret, if two of them are dead." - Benjamin Franklin



blog comments powered by Disqus

Who is Rahul?


He works for Microsoft and likes Software & Gadgets!

He shares some interesting notes here while working with stuff that excites him.


The opinions expressed herein are our own personal opinions and do not represent our employer's view in any way.
© Copyright 2014, Rahul Soni