You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历远程计算机时遇RPC不可用错误,如何在foreach循环中继续执行?

处理RPC不可用错误并继续遍历远程计算机列表

在PowerShell中,要实现遇到RPC不可用错误时跳过当前计算机、继续遍历的需求,核心思路是通过**try/catch块捕获特定错误**,结合强制终止错误的参数来触发捕获逻辑。以下是具体实现方法:

核心实现方案(WMI方法)

针对你使用Invoke-WmiMethod的场景,通过指定-ErrorAction Stop将非终止错误转为终止错误,再捕获对应RPC异常:

# 定义需要遍历的远程计算机列表
$targetComputers = @("PC-001", "PC-002", "PC-003")

foreach ($computer in $targetComputers) {
    try {
        # 执行WMI调用,强制将错误转为终止型以便捕获
        Invoke-WmiMethod -ComputerName $computer -Class Win32_OperatingSystem -Name GetLastBootUpTime -ErrorAction Stop
        
        # 这里可以添加其他需要执行的扫描操作
        Write-Host "✅ 成功处理计算机: $computer"
    }
    catch [System.Management.ManagementException] {
        # 精准匹配RPC服务器不可用错误(错误代码0x800706BA)
        if ($_.Exception.ErrorCode -eq 0x800706BA) {
            Write-Warning "⚠️ 计算机 $computer 出现RPC服务器不可用错误,已跳过"
        }
        else {
            # 处理其他WMI相关异常
            Write-Error "❌ 处理计算机 $computer 时发生其他WMI错误: $_"
        }
    }
    catch {
        # 处理非WMI类的未知错误
        Write-Error "❌ 处理计算机 $computer 时发生未知错误: $_"
    }
}

替代方案(CIM方法,推荐PowerShell 5.1+)

如果环境支持,使用Invoke-CimMethod(WMI的现代替代)的错误处理更一致,实现逻辑类似:

foreach ($computer in $targetComputers) {
    try {
        Invoke-CimMethod -ComputerName $computer -ClassName Win32_OperatingSystem -MethodName GetLastBootUpTime -ErrorAction Stop
        Write-Host "✅ 成功处理计算机: $computer"
    }
    catch [Microsoft.Management.Infrastructure.CimException] {
        # CIM中RPC错误的HResult同样为0x800706BA
        if ($_.Exception.HResult -eq 0x800706BA) {
            Write-Warning "⚠️ 计算机 $computer 出现RPC服务器不可用错误,已跳过"
        }
        else {
            Write-Error "❌ 处理计算机 $computer 时发生其他CIM错误: $_"
        }
    }
    catch {
        Write-Error "❌ 处理计算机 $computer 时发生未知错误: $_"
    }
}

关键注意事项

  1. -ErrorAction Stop的必要性:PowerShell默认将WMI/CIM的多数错误标记为非终止错误,不会触发catch块,必须通过该参数强制转为终止错误才能被捕获。
  2. 精准捕获错误:通过匹配特定异常类型和错误代码(0x800706BA),避免误捕获其他无关错误,确保只跳过RPC不可用的设备。
  3. 错误记录:通过Write-Warning或日志工具记录跳过的设备,方便后续确认需要更换/重新映像的目标。

内容的提问来源于stack exchange,提问作者Jeremy Patrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 16:19:59