Get Exit Code From Start-Process in PowerShell

John Wachira Nov 01, 2022
Get Exit Code From Start-Process in PowerShell

This article illustrates how we can obtain the exit code from the Start-Process command in PowerShell.

The Start-Process cmdlet allows us to run one or more processes in our machines from PowerShell. You can use the cmdlet to start an application on your computer.

Get Exit Code From Start-Process in PowerShell

When you run a PowerShell script, the console always returns the status of the execution. PowerShell returns zero when a script is executed successfully, while an unsuccessful execution returns a non-zero value.

The value resulting from an unsuccessful script execution is called an Error Code.

How can we get the exit code from Start-Process? Let’s use an example to explain the concept.

Let’s say we want to open Notepad from PowerShell and get the exit code for the script. How do we go about it?

Let’s start with defining a script to open Notepad from PowerShell. We will use the Start-Process cmdlet as illustrated below:

Start-Process -FilePath "notepad.exe" -PassThru -Wait

This script will open Notepad and wait for us to exit manually. However, we need to save the command in a variable to get the exit code.

In our case, we will save it in the variable $run. Our script will read:

$run = (Start-Process -FilePath "notepad.exe" -PassThru -Wait)

After exiting Notepad, we can now get the exit code as illustrated below:

$run.ExitCode

This will return 0 since the script was executed successfully.

exit code 1

What if, after starting Notepad, we want some processing to run in the background? In such a situation, we will omit the -wait and instead use $run.WaitExit(), as illustrated below:

$run = (Start-Process -FilePath "notepad.exe" -PassThru)
$run.WaitExit()

After exiting Notepad, we can get the exit code, as shown below:

$run.ExitCode

This will still return 0 since the script was successful.

In conclusion, you can get the exit code from the Start-Process cmdlet by saving the command in a variable. This will allow you to run the $.ExitCode command to get the exit code.

If you get a non-zero value, it shows that the script was not executed successfully.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn