How to extract $ lastexitcode from c # powershell execution script

I have a script running in C # using the async powershell startup code for the project code here:

http://www.codeproject.com/KB/threads/AsyncPowerShell.aspx?display=PrintAll&fid=407636&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2130851#xx2130851xx

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

In this engine, I need to make sure that the script runs correctly.

Any help would be appreciated.

Regards, Bob.

Its $ lastexitcode and $? the variables that I need to return.

Hi, Finally answered.
I learned about the $ host variable. It implements a callback to the host, in particular the custom PSHost object, allowing you to return $ lastexitcode. Here is a link to the explanation of $ host.

http://mshforfun.blogspot.com/2006/08/do-you-know-there-is-host-variable.html

This seems to be unclear, poorly documented, as usual, with powershell documents. Using point 4, calling $ host.SetShouldExit (1) returns 1 to the SetShouldExit method for pshost, as described here.

http://msdn.microsoft.com/en-us/library/system.management.automation.host.pshost.setshouldexit(VS.85).aspx

In reality, it depends on the definition of your own exit code. 0 and 1 suffixes, I think.

Regards, Bob.

+4
source share
3 answers

Here is a function you can try:

function run-process ($cmd, $params) { $p = new-object System.Diagnostics.Process $p.StartInfo = new-object System.Diagnostics.ProcessStartInfo $exitcode = $false $p.StartInfo.FileName = $cmd $p.StartInfo.Arguments = $params $p.StartInfo.UseShellExecute = $shell $p.StartInfo.WindowStyle = 1; #hidden. Comment out this line to show output in separate console $null = $p.Start() $p.WaitForExit() $exitcode = $p.ExitCode $p.Dispose() return $exitcode } 

Hope that helps

+4
source

You can write script code that will check the $ lastexitcode code, and throw an exception if the exit code is not what you are freed from.
Exceptions are easier to catch.

+1
source

I believe that you are making a mountain out of flies using this code project. Asynchronous execution is very easy to do in C #.

 PowerShell psCmd = PowerShell.Create().AddScript({Invoke-YourScriptAndReturnLastExitCode}); IAsyncResult result = psCmd.BeginInvoke(); // wait for finish psCmd.EndInvoke(result); 

Also, looking at your question about this project, it looks like you are trying to use TFS in PowerShell. You may consider the following additional information:

  • TFS has cmdlets
  • Many other people have worked with TFS cmdlets, i.e. Pstfs
  • You can always copy the tfs executable file wherever you need it, which wraps at least part of your scripting problems.

Hope this helps

+1
source

All Articles