exception - 不可捕获的异常(PowerShell)

标签 exception powershell try-catch

我有可靠地生成异常的代码。这是预期的,因此当我转储$ error变量以查找实际问题时,我不希望它显示在脚本的末尾。

步骤1是找到此异常并进行处理,对吗?我走不了那么远。这是我所拥有的:

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
+如果((Get-PSSnapin <<<< -Name $ SnapInName)-eq $ null){
+ CategoryInfo:InvalidArgument:(Microsoft.Excha ... owerShell.Admin:String)[Get-PSSnapin],PSArgumentException
+ FullyQualifiedErrorId:NoPSSnapInsFound,Microsoft.PowerShell.Commands.GetPSSnapinCommand

编辑:预先感谢您抽出宝贵时间来帮助我!

最佳答案

您应该将-ErrorAction stop添加到Get-PSSnapin中以进入捕获块。

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"

关于exception - 不可捕获的异常(PowerShell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18500423/

相关文章:

c# - Xamarin、MySQL 异常 : unable to connect to any specific host

powershell - 如何通过powershell重命名azure订阅名称

Python:如何在遇到超时时重试

PowerShell 获取内容 -ReadCount

powershell - Pester 模拟 CmdLets

php - try catch 我的整个 PHP 代码或尽可能具体是最佳实践吗?

C# 是否存在异常 ID

java - 在 EJB 中使用 SSL 出现异常 : Keystore was tampered with, 或密码不正确

ios - NSArray : 'NSInvalidArgumentException' 上无法识别的选择器

c# - 如何通过 C# 中的异常处理理解 "using"的 JITed 代码