How to catch Exceptions with PowerShell

Solution 1:

The GetWMICOMException is a non-terminating error, meaning that with a default $ErrorActionPreference of Continue, the code in the try block is going to continue its execution after writing out the exception as an error

Enclose the Get-WmiObject call with a try-catch block, but make sure that the -ErrorAction is set to Stop:

# Try-Catch block starts
try 
{
    # Call Get-WmiObject
    Get-WmiObject -ComputerName $computer -Class "Win32_NetworkAdapter" -ErrorAction Stop
}
# If an Exception of the type COMException is thrown, execute this block
catch [System.Runtime.InteropServices.COMException]
{
    # You can inspect the error code to see what specific error we're dealing with 
    if($_.Exception.ErrorCode -eq 0x800706BA)
    {
        # This is instead of the "RPC Server Unavailable" error
        Write-Error -Message "Your own custom message" 
    }
    else
    {
        Write-Error -Message "Some other COMException was thrown"
    }
}
# If any other type of Exception is thrown, execute this block
catch [System.Exception]
{
    Write-Error -Message "Some other exception that's nothing like the above examples"
}
# When all of the above has executed, this block will execute
finally
{
    Write-Verbose "Get-WmiObject object was executed"
}

Alternatively, you could set the $ErrorActionPreference to Stop before executing your script:

# Before the rest of the script
$ErrorActionPreference = Stop

For more help about the try-catch-finally construction:

Get-Help about_Try_Catch_Finally -Full

For more help about the $*Preference vars:

Get-Help about_Preference_variables -Full