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

能否在PowerShell函数中为Try/Catch块的数组设置不同名称?

在PowerShell的Try/Catch中分别维护成功与失败数组

完全可以实现这个需求,核心是在Try/Catch代码块外部初始化两个空数组,确保作用域覆盖整个流程,然后分别在Try(成功分支)和Catch(失败分支)中向对应数组添加对象。以下是完整示例:

# 初始化两个空数组,作用域覆盖后续的Try/Catch
$computerArray = @()
$computerArray2 = @()

# 示例计算机列表
$computers = "PC01", "PC02", "InvalidPC", "PC03"

foreach ($computer in $computers) {
    try {
        # 先尝试Ping验证(可选,根据你的需求调整)
        if (-not (Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction Stop)) {
            throw "无法Ping通计算机"
        }

        # 执行Invoke-Command(替换为你的实际操作)
        $result = Invoke-Command -ComputerName $computer -ScriptBlock {
            [PSCustomObject]@{
                ComputerName = $env:COMPUTERNAME
                OSVersion    = [Environment]::OSVersion.VersionString
                Status       = "成功"
            }
        } -ErrorAction Stop

        # 将成功结果添加到成功数组
        $computerArray += $result
    }
    catch {
        # 捕获所有错误,创建失败信息对象
        $errorObject = [PSCustomObject]@{
            ComputerName = $computer
            ErrorMessage = $_.Exception.Message
            Status       = "失败"
        }

        # 将失败信息添加到失败数组
        $computerArray2 += $errorObject
    }
}

# 按需求分开输出结果
Write-Host "Results"
Write-Output $computerArray

Write-Host "Failed: computerlist" -ForegroundColor Red
Write-Output $computerArray2

# 如需导出CSV,直接调用Export-Csv即可
# $computerArray | Export-Csv -Path "成功结果.csv" -NoTypeInformation
# $computerArray2 | Export-Csv -Path "失败结果.csv" -NoTypeInformation

关键注意点:

  • 数组初始化位置:必须在Try/Catch外部定义$computerArray和$computerArray2,如果在Try或Catch内部定义,变量会被限制在局部作用域,外部无法访问。
  • 错误处理逻辑:通过-ErrorAction Stop将非终止错误转为终止错误,确保能进入Catch块;在Catch中通过$_.Exception.Message获取具体错误信息,也可以根据需要提取更多错误详情。
  • 对象一致性:成功和失败的对象最好保持相同的属性结构(比如都包含ComputerName、Status),这样后续导出CSV或处理数据时格式统一,更方便使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:15:43