Eds
Eds

Reputation: 575

Assistance with first time Powershell Exception catching

I am not much of a programmer, and only occasionally use powershell to accomplish some of my tasks, and as such, have never done any real error handling in my powershell scripts/commands.

I am struggling to wrap my head around catching exceptions in my example code below, as it seems to be behaving the wrong way around. here is the code:

$Computers = Get-ADComputer -SearchBase 
"OU=Desktops,OU=Computers,OU=Managed,DC=domain,DC=local" -Filter * | select Name
$Table= ""
$Computers | Foreach  {
    $Name = $_.Name
    try {
        $Table += Get-WmiObject -Class Win32_Product -ComputerName $Name | 
        Where-Object {$_.Name -eq "Product Name"} | select PSComputerName,Name,Version
    }
    catch {
        $Name + " unavailable"
    }
}

What seems to happen, is when a computer is off or otherwise unavailable, the Get-WmiObject command fails, and displays an Exception message in the powershell window. I would have expected my Catch statement to see this exception, and instead output the $Name of the computer and the text " Unavailable".

When I say it happens backwards, after displaying the exception message for the unavailable computers, for those that are successful it shows the $Name + " unavailable".

Am I misundertsanding the concept behind error handling in powershell, and how can I adjust the above code to catch the erroring computers and do something different with them?

Upvotes: 0

Views: 59

Answers (2)

Ryan McVicar
Ryan McVicar

Reputation: 103

You need to add -ErrorAction Stop to your Get-WMIObject call.

Example:

try{
    Get-WmiObject -Class asdf -ErrorAction Stop
}
catch{
    Write-Host error!
}

returns

error!

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

Get-WmiObject throws what's known as a non-terminating error - in order to have execution terminate on error and have the catch block execute, you need to specify -ErrorAction Stop when calling it:

try {
    $Table += Get-WmiObject -Class Win32_Product -ComputerName $Name -ErrorAction Stop |Where-Object {$_.Name -eq "Product Name"} | select PSComputerName,Name,Version
}
catch {
    $Name + " unavailable"
}

Upvotes: 3

Related Questions