【问题标题】:Uncatchable Exception (PowerShell)无法捕获的异常 (PowerShell)
【发布时间】:2013-09-01 06:22:45
【问题描述】:

我有可靠地生成异常的代码。这是意料之中的,所以当我转储 $error 变量以查找实际问题时,我不希望它出现在脚本末尾。

第一步是找到这个异常并处理它,对吧?我不能走那么远。这是我所拥有的:

Function Add-PowerShellSnapIn($SnapInName){
    Try{
        if ((Get-PSSnapin -Name $SnapInName) -eq $null){
            Write-Warning "SnapIn Is Not Already Loaded"
        }
    }Catch [System.Exception]{
        Write-Warning "Error Caught"
    }
}

Add-PowerShellSnapIn -SnapInName "Microsoft.Exchange.Management.PowerShell.Admin"

如果我运行此代码,我可以看到异常,但我从来没有看到我的小“写警告”测试消息表明 Catch 块捕获了异常。我一定在这里遗漏了一些东西。这是我看到的异常:

Get-PSSnapin:找不到与模式“Microsoft.Exchange.Management.PowerShell.Admin”匹配的 Windows PowerShell 管理单元。检查模式,然后重试该命令。 在 C:\users\myuser\Desktop\Test.ps1:4 char:20 + if ((Get-PSSnapin

编辑:提前感谢任何花时间帮助我的人!

【问题讨论】:

    标签: exception powershell try-catch


    【解决方案1】:

    您应该将 -ErrorAction stop 添加到您的 Get-PSSnapin 以进入 Catch Block。

    Function Add-PowerShellSnapIn($SnapInName){
        Try{
            if ((Get-PSSnapin -Name $SnapInName -ErrorAction Stop) -eq $null){
                Write-Warning "SnapIn Is Not Already Loaded"
            }
        }Catch [System.Exception]{
            Write-Warning "Error Caught"
        }
    }
    
    Add-PowerShellSnapIn -SnapInName "Microsoft.Exchange.Management.PowerShell.Admin"
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2013-06-25
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 2011-04-19
      • 2019-12-17
      • 2021-10-09
      相关资源
      最近更新 更多