Home > Software design >  Returning exit 0/1 from powershell/Bash Script
Returning exit 0/1 from powershell/Bash Script

Time:07-23

I am calling an exe(c# code) from my powershell script (Can use bash too) and it works fine.

Now, I want to return something like true/false from my exe and if it is true then my other bash script will return exit 0 else exit 1.

My current ps script is something like this :

& C:\Users\location\Test.exe Parameter1

How can I achieve this ?

CodePudding user response:

you can start your exe in a process and get the return code. (with $EXECUTABLE and $arglist containing the executable paht and the arguments to pass respectively)

$process = Start-Process $EXECUTABLE -argumentlist $arglist -Wait

# check the exit code of the process
if (0 -eq $process.ExitCode) {
    exit 0
}
exit 1

CodePudding user response:

Assuming that your C# application is a console application:

  • Make it return an int from its Main method, which becomes the process exit code when your application is called; by convention, an exit code of 0 signals success, whereas any non-zero value indicates failure.

On the scripting side:

  • Bash:

    • If the call to your C# executable is the last command in your script, its exit code will implicitly be passed through, i.e. it will become the script's exit code; otherwise, save the exit code, as reported in the built-in $? variable, in a variable and pass that to exit later.
  • PowerShell:

    • PowerShell reports the exit code of the most recently executed external program in its automatic $LastExitCode variable.

    • Unlike in Bash, exit codes are never automatically passed through, so you'll need to do the following to make your PowerShell script report your C# application's exit code:

      & C:\Users\location\Test.exe Parameter1
      exit $LASTEXITCODE
      

Note that there's rarely a good reason to use Start-Process to invoke console applications in PowerShell. Direct invocation, as shown in your question, ensures:

  • synchronous (blocking) execution
  • that the application's output streams (stdout, stderr) are connected to PowerShell's streams, allowing them to be captured
  • reporting of the process exit code in $LASTEXITCODE
  • Related