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.

Interesting:   WMI/netsh to add DNS servers on network adapters

$LASTEXITCODE the equivalent to %ERRORLEVEL%.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Hi! Join the discussion, leave a reply!