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

PowerShell多Catch语句失效求助:单Catch正常多Catch仍报错

PowerShell GUI脚本多Catch块无法捕获错误的解决方法

你的问题核心在于PowerShell默认仅将终止错误交给try/catch处理,而Get-Acl遇到权限不足或路径不存在时,抛出的是非终止错误——这类错误不会触发catch块,只会直接输出到控制台。单个catch块能正常工作可能是你之前隐式设置了错误行为(比如全局$ErrorActionPreference = 'Stop'),但多catch块场景下该设置未生效。

解决方案

要让错误进入catch流程,必须强制将非终止错误转为终止错误,有两种可靠方式:

  • 在Get-Acl命令后添加-ErrorAction Stop参数(仅作用于该命令)
  • 在try块开头设置$ErrorActionPreference = 'Stop'(作用于整个try块范围)

另外,当前代码存在额外隐患:当catch触发时,$acl仍是初始的空哈希表@{},后续执行foreach ($Access in $acl.Access)会抛出新错误(空哈希表无Access属性)。需将foreach逻辑移到try块内,仅当Get-Acl成功时执行。

修改后的代码示例

$buttonShares.Add_Click(
{
    $listBoxItem = $listBoxGroup.SelectedItem.ToString().Trim()
    $path = "\\kpd-srv-10\$listBoxItem"
    $listBoxShares.Items.Clear()

    try
    {
        # 强制将非终止错误转为终止错误,确保catch能捕获
        $acl = Get-Acl -Path $path -ErrorAction Stop
        $listBoxShares.Items.Clear()

        # 仅当Get-Acl成功时,才遍历权限项
        foreach ($Access in $acl.Access)
        {
            if($Access.IdentityReference -notlike "PBL*")
            {
                continue
            }
            $listBoxShares.Items.Add($Access.IdentityReference)
        }
    }
    catch [System.UnauthorizedAccessException]
    {
        $listBoxShares.Items.Add("keine Berechtigung")
    }
    catch [System.ItemNotFoundException]
    {
        $listBoxShares.Items.Add("Laufwerk konnte nicht gefunden werden")
    }
    catch
    {
        $listBoxShares.Items.Add("Es ist ein Fehler aufgetreten!")
    }
}) 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:58:05