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:
if($?) {
  # True, last operation succeeded

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

Disk cleanup with Dism example

To illustrate the PowerShell errorlevel usage, 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
# 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."


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

$LASTEXITCODE the equivalent to %ERRORLEVEL%.

Want to say thanks?

If I’ve helped you out and you want to thank me, why not buy me a coffee?

If I’ve helped you out and you want to thank me, why not buy me a coffee?

Thank you for your support.