【问题标题】:Try-Catch: Why I'm still having uncaught errors? [duplicate]Try-Catch:为什么我仍然有未捕获的错误? [复制]
【发布时间】:2023-03-13 13:59:01
【问题描述】:

我正在运行以下脚本来确定服务器上是否有驱动器 Z:。它包含try/catch,但我仍然收到“RPC-server is not available”这样的错误:

Get-WmiObject : RPC 服务器不可用。 (来自 HRESULT 的异常:0x800706BA) 在 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
    }
}

【问题讨论】:

    标签: powershell error-handling try-catch


    【解决方案1】:

    powershell 中的某些内容会引发非终止错误,这些错误不会触发 on-error 事件。

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

    【讨论】:

    • 谢谢!这似乎已经解决了这个问题!
    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2017-07-25
    • 2022-12-21
    相关资源
    最近更新 更多