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

 try
{
    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);
p.WaitForExit();
if (p.ExitCode == 100)
{
     // Do something for Success
}
else
{
     // Do something for failure
}

 

Hope this helps, Wave
Rahul

 


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

Tags:

PowerShell

blog comments powered by Disqus

Disclaimer

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