Search code examples
powershellcmderror-handlingdism

Handle DISM errors from PowerShell script


How can I capture errors when using DISM tool from PowerShell script?

& cmd /c 'DISM /online /disable-feature /NoRestart /featurename:[feature_name] >NUL 2>&1'

if ($LASTEXITCODE -ne 0) {
    Write-Host "ERROR"
} else {
    Write-Host "SUCCESS"
}

Whether [feature_name] exists or not, I always get ERROR.

However it works if I replace the cmd command with another, for example

& cmd /c 'dir [some_file] >NUL 2>&1'

If [some_file] exists I get SUCCESS, otherwise ERROR.


Solution

  • It seems that the exit code for success returned by DISM is 3010 instead of 0.

    This works for DISM commands within PowerShell:

    if ($LASTEXITCODE -ne 3010) {
        ...
    } else {
        ...
    }