6

Does anyone know how to get the return code from a .NET executable? I've written a program that has a static main method that returns an int and I can't seem to get this number when I run it from powershell. This is what I currently have:

&$executable $params
exit $LASTEXITCODE

where $executable is the path to the executable and $params are the parameters passed to the executable.

However, $LASTEXITCODE is always 0. The program writes to the console via a Log4Net console appender so the above pipes the output to the console in PowerShell.

Can anyone help?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
BigBytes
  • 339
  • 6
  • 19

2 Answers2

4
(Start-Process -FilePath 'exe' -ArgumentList @() -PassThru -Wait).ExitCode

This will grab your exit code after execution completes. You could even assign it to a variable and access the process members if you want.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
2

Sounds to me like your executable doesn't return an exit code (i.e., Environment.Exit()) but instead outputs a result code (e.g., Console.Write()).

Try something like:

$ReturnValue = &$executable $params
Exit $ReturnValue
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
  • 1
    The executable has a static main method which returns an int which I assumed would be the equivalent of an exit code but maybe I need to try Enivronment.Exit() with an exit code. There is no Console.Write(). I will try what you suggested though and let you know if it works. – BigBytes Sep 08 '17 at 14:39
  • @BigBytes You may want to take a look at [this question](https://stackoverflow.com/questions/155610/how-do-i-specify-the-exit-code-of-a-console-application-in-net). TLDR is either `Environment.Exit(value)` or `return value` should work. – Bacon Bits Sep 08 '17 at 14:50
  • Doesn't work. I'm trying Environment.Exit(1) and using:- &$executable $params Exit $LastExitCode But this doesn't work. It still thinks the return code is 0. What am I doing wrong? – BigBytes Sep 08 '17 at 15:14
  • $ReturnValue = &$executable $params Exit $ReturnValue doesn't work either – BigBytes Sep 08 '17 at 15:15
  • @BigBytes Hm. I've not seen that. Try running it using one of the methods in [this answer](https://stackoverflow.com/a/10262275/696808). – Bacon Bits Sep 08 '17 at 22:32