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?

2
  • 1
    There's nothing wrong with your PowerShell code. Please show the code of your .Net program. Commented Sep 8, 2017 at 15:20
  • I'm doing Environment.Exit(1) at the end of my static void Main() method Commented Sep 8, 2017 at 15:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Nope this didn't work. Exit code that comes back is still 0. My program is definitely setting the error code to 1 so I'm not sure why it always comes back at 0
@BigBytes If it's not capturing your exit code, your program apparently isn't returning non-zero.
(Start-Process -FilePath 'exe' -ArgumentList @() -PassThru -Wait).ExitCode did the trick
@BigBytes The ArgumentList is where an array of arguments would go, for example: $Params
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

5 Comments

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 You may want to take a look at this question. TLDR is either Environment.Exit(value) or return value should work.
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?
$ReturnValue = &$executable $params Exit $ReturnValue doesn't work either
@BigBytes Hm. I've not seen that. Try running it using one of the methods in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.