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



blog comments powered by Disqus

Rahul Soni

Rahul Soni  Twitter

 LinkedIn

 Facebook

 Email me



Vivek Kumbhar

Vivek Kumbhar  Twitter

 LinkedIn

 Facebook

 Email me


Stack Exchange

profile for Vivek at Server Fault, Q&A for system administrators and IT professionals

profile for Rahul Soni at Stack Overflow, Q&A for professional and enthusiast programmers

Calendar

<<  May 2013  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

All Items
Sign in

Visit Microsoft's Site

Disclaimer

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

Powered by BlogEngine.NET 1.4.5.0