Try-Catch: Why I'm still having uncaught errors?

1

I'm running the following script to identify whether there is drive Z: on a server. It contains try/catch, but I'm still getting "RPC-server is not available" errors like this:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\Users\vlitovch\Documents\Get-DriveZRemotely.ps1:19 char:26
+ ...        $a = Get-WmiObject Win32_LogicalDisk -ComputerName $($comp.DNS ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

for the hosts that are listed in AD, but don't exist. Why? And on the top of this for these hosts I have "Cannot get disks" error message as well, so they don't fall into the catch block.

function Get-Moment {
    Get-Date -Format 'MM/dd/yyyy HH:mm:ss'
}

#if (Test-Path -Path $logFile1) {Remove-Item -Path $logFile1 }
ipmo ActiveDirectory
$Servers = Get-ADComputer -Filter 'Name -like "*"' -SearchBase 'OU=Production,OU=Windows,OU=Servers,DC=contoso,DC=com'
foreach ($comp in $Servers) {
    "INFO $(Get-Moment) Host:$($comp.DNSHostName)" | Write-Output
    try {
        $a = Get-WmiObject Win32_LogicalDisk -ComputerName $($comp.DNSHostName)
    } catch {
        "EROR $(Get-Moment) Host:$($comp.DNSHostName) Couldn't reach the host!" | Write-Output
        continue
    }

    if ($a) {
        $diskz = $false
        foreach ($disk in $a) {
            if ($disk.DeviceID -eq 'Z:') {$diskz = $true}
        }
        if (!$diskz) {
            "EROR $(Get-Moment) Host:$($comp.DNSHostName) Disk Z: is absent." | Write-Output
        }
    } else {
        "EROR $(Get-Moment) Host:$($comp.DNSHostName) Cannot get disks" | Write-Output
    }
}
powershell
error-handling
try-catch
asked on Stack Overflow May 22, 2017 by Papa Smurf • edited May 22, 2017 by Ansgar Wiechers

1 Answer

4

Some things in powershell throw non-terminating errors, which do not trigger on-error events.

adding -ErrorAction Stop to the end of the Get-WmiObject command will force it to become terminating, and thus trigger the try{}catch{} block.

answered on Stack Overflow May 22, 2017 by colsw

User contributions licensed under CC BY-SA 3.0