Check last exit code with PowerShell

In a script containing a lot of commands, it could be very helpful to be able to check if their execution are successful or not.

To check the last exit code returned in a PowerShell script, the variable $lastExitCode can be used.

$lastExitCode contains the exit code of the last Win32 executable execution.

Here is an example:

# First ExitCode : Success
#=================================================================================================================================

Write-Host "First Test : Ping 127.0.0.1 - should be success (0)"
Write-Host ""
ping 127.0.0.1
Write-Host ""
Write-Host "First exit code is $lastExitCode"
Write-Host ""
If ($lastExitCode -eq "0") {
    Write-Host "Success !!"
}

If ($lastExitCode -eq "1") {
    Write-Host "Failure..."
}
Write-Host ""
Write-Host "----------------------------------------------------------------"
Write-Host ""
Write-Host ""



# Second ExitCode : Failure
#=================================================================================================================================

Write-Host "Second Test : Ping NotExisting - should be failure (1)"
Write-Host ""
ping NotExisting
Write-Host ""
Write-Host "Second exit code is $lastExitCode"
Write-Host ""
If ($lastExitCode -eq "0") {
    Write-Host "Success !!"
}

If ($lastExitCode -eq "1") {
    Write-Host "Failure..."
}
Write-Host ""
Write-Host "----------------------------------------------------------------"
Write-Host ""
Write-Host ""



# Third ExitCode : Success
#=================================================================================================================================

Write-Host "Third Test : Ping 127.0.0.1 - should be success again (0)"
Write-Host ""
ping 127.0.0.1
Write-Host ""
Write-Host "Third exit code is $lastExitCode"
Write-Host ""
If ($lastExitCode -eq "0") {
    Write-Host "Success !!"
}

If ($lastExitCode -eq "1") {
    Write-Host "Failure..."
}
Write-Host ""
Write-Host "----------------------------------------------------------------"
Write-Host ""
Write-Host ""