How to extract $lastexitcode from c# powershell script execution


I’ve got a scipt executing in C# using the powershell async execution code on code project here:

I need to return the $lastexitcode and Jean-Paul describes how you can use a custom pshost class to return it. I can’t find any method or property in pshost that returns the exit code.

This engine I have needs to ensure that script executes correctly.

Any help would be appreciated.


Its the $lastexitcode and the $? variables I need to bring back.

Finally answered.
I found out about the $host variable. It implements a callback into the host, specifically a custom PSHost object, enabling you to return the $lastexitcode. Here is a link to an explanation of $host.

It seems to be obscure, badly documented, as usual with powershell docs. Using point 4, calling $host.SetShouldExit(1) returns 1 to the SetShouldExit method of pshost, as described here.

Its really depends on defining your own exit code defintion. 0 and 1 suffixes I guess.



Here is a function you can try:

Hope that helps


How to extract $lastexitcode from c# powershell script execution by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply