Beto
Beto

Reputation: 171

How to run a command with options and store exit code in a variable

Hello Stack Overflow experts

I am currently trying to run an exe file from a PowerShell script, and would like to store the exit code in a variable.

If run from the Windows command line on its own, the syntax is as follows:

C:\MyProgram\mycommand.exe --option1=value1 --option2=value2 --option3=value3

In Powershell, I can run the above using the call operator:

$myExe="C:\MyProgram\mycommand.exe"
$options = @(
                "--option1=value1"
                "--option2=value2"
                "--option3=value3"
            )
& $myExe @options

but I'm not sure how to assign the exit code returned by the exe file into a variable.

So far, this is what I have tried:

  1. Tried the following syntax:
$myVariable | & $myExe @options

but the variable does not get assigned a value

  1. Used Tee-Object
& $myExe @options | Tee-Object $myVariable

but I get a ParameterBindingValidationException error

  1. Created a System.Diagnostics.Process object
$ps = New-Object System.Diagnostics.Process
$ps.StartInfo.FileName = "C:\MyProgram\mycommand.exe"
$ps.StartInfo.Arguments = "--option1=value1 --option2=value2 --option3=value3"
$ps.StartInfo.RedirectStandardOutput = $True
$ps.StartInfo.UseShellExecute = $False
$ps.Start()
$ps.WaitForExit()

which allows me to get the exit code by calling $ps.ExitCode, but the exe is not running correctly. No errors are thrown, but it looks like the options are not being read correctly.

Any deas on how this can be achieved?

Upvotes: 0

Views: 1310

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

After the executable exits, PowerShell will populate the $LASTEXITCODE variable with the exit code:

$myExe="C:\MyProgram\mycommand.exe"
$options = @(
                "--option1=value1"
                "--option2=value2"
                "--option3=value3"
            )
$outputFromExe = & $myExe @options

return [pscustomobject]@{
  Program = $myExe
  ExitCode = $LASTEXITCODE
  Output = $outputFromExe
}

Upvotes: 2

Related Questions