PowerShell return value, exit code, or ErrorLevel equivalent

Here is how you can verify whether an external command in PowerShell was executed successfully or not by its errorlevel. Simply by verifying PowerShell’s return value, or exit code…

Powershell $? operator #

The PowerShell operator $? contains True if the last operation succeeded and False otherwise.

# source:
# http://blogs.msdn.com/b/powershell/archive/2006/09/15/errorlevel-equivalent.aspx
if($?) {
  # True, last operation succeeded

if (!$?) {
  # Not True, last operation failed

Disk cleanup with Dism example #

To illustrate the above, have a look at the Cleanup-Image command of Deployment Image Servicing and Management (DISM). In my Windows Server 2012 (R2) disk cleanup – DISM post, I’ve shown you how to clean up your Windows Server 2012 R2 WinSxs folder with DISM. Those commands are easily wrapped into a PowerShell script.

Here a small PowerShell snippet:

$os_version = [System.Environment]::OSVersion.Version
# The above returns 6.3.9600.0 for Server 2012 R2 or 
# 10.0.14393.0 for Server 2016. Server 2012 matches 
# 6.2.9200.0, and so on.
# See https://msdn.microsoft.com/nl-nl/library/windows/desktop/ms724832(v=vs.85).aspx
# for more information about Windows Server versions.

$cleanup = $false

# Always be careful comparing strings and integers!
if ( $os_version -ge ( New-Object System.Version "10.0" ) ) {
    # $os_version is greater than, or equal to "10.0", so 
    # this is Windows Server 2016.

if ( $os_version -ge ( New-Object System.Version "6.3" ) -And $os_version -le ( New-Object System.Version "10.0" ) ) {
    # $os_version is greater than 6.3 and smaller than 10.0,
    # therefore this must be Windows Server 2012 R2

    &dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase `
        | Write-Output
    if ($?) {
        # dism cleanup-image was successful, set variable to True
        $cleanup = $true
if ( $cleanup ) {
    # Dism.exe was executed
    Write-Host "[*] System going down for reboot in 3 seconds!"
    &shutdown /r /f /t 3
} else {
    # an error occured
    Write-Host "[*] Something went wrong with DISM and Cleanup-Image, `
      please perform the actions by hand."

PowerShell’s $LASTEXITCODE #

The PowerShell $LASTEXITCODE should be 0, since $LASTEXITCODE contains the exit code of the last Win32 executable execution.

This may interest you:   How to determine if a SQL Server backup is compressed?

$LASTEXITCODE the equivalent to %ERRORLEVEL%.

About the Author Jan Reilink

My name is Jan. I am not a hacker, coder, developer, programmer or guru. I am merely a system administrator, doing my daily thing at Vevida in the Netherlands. With over 15 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization.

follow me on:

Leave a Comment: