Try-Catch:为什么我还有未捕获的错误?

时间:2017-05-22 11:02:16

标签: powershell error-handling try-catch

我正在运行以下脚本来确定服务器上是否有驱动器Z :.它包含try / catch,但我仍然得到“RPC-server not available”错误,如下所示:

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

表示AD中列出的主机,但不存在。为什么?对于这些主机而言,我还有“无法获取磁盘”错误消息,因此它们不属于catch块。

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
    }
}

1 个答案:

答案 0 :(得分:4)

powershell中的一些内容会抛出非终止错误,这些错误不会触发错误事件。

-ErrorAction Stop添加到Get-WmiObject命令的末尾将强制它终止,从而触发try{}catch{}阻止。