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

by Rahul 12/26/2012 11:56:00 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

Tags: , ,

PowerShell | Tips and Tricks | Troubleshooting

blog comments powered by Disqus