3

Looking for the PowerShell equivalent of this cmd error-check:

IF %ERRORLEVEL% NEQ 0

Here is the PowerShell code I am trying to write:

Write-Information "Installing .NET 3 from DVD:"
$NetFX3_Source = "D:\Sources\SxS"
dism /online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:$NetFX3_Source /NoRestart
IF (****TheCommandYouTellMe****) {
Write-Information "DVD not found, installing from online sources, the Win default method"
DISM.EXE /Online /Add-Capability /CapabilityName:NetFx3~~~~
Add-WindowsCapability –Online -Name NetFx3~~~~
}
Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35
gregg
  • 1,084
  • 1
  • 12
  • 25

2 Answers2

5

Since dism.exe is an external program, you'd want to check the $LASTEXITCODE automatic variable:

dism /online /andsoon
if($LASTEXITCODE -ne 0)
{
    # Add your capability
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
2

Mathias R. Jessen's answer acually answers the specific question but not the entirety of PowerShell equivalent of cmd "IF %ERRORLEVEL% NEQ 0" (it did not do the job for me since I want to check dir error that is an internal program and $LASTEXITCODE is only for external programs as I understood), a more generic test would be:

dism ...
if ($? -ne $true) {
    # Add your capability
}

Or:

dism ...
if ($? -eq $false) {
    # Add your capability
}

But while it is more generic, it is less flexible since I assume programs setting $LASTEXITCODE can return different code depending on what happened during execution then react differently depending on situation, whereas with $? we have only success ($true) or fail ($false), for instance:

if ($LASTEXITCODE -eq 0)
{
    echo Success
}
elseif ($LASTEXITCODE -eq 1)
{
    # Treat whatever last exit code = 1 means
}
elseif ($LASTEXITCODE -eq 2)
{
    # Treat whatever last exit code = 2 means
}
...
gluttony
  • 402
  • 6
  • 14