Exception 不可修补异常(PowerShell)
我有可靠生成异常的代码。这是预期的,所以当我转储$error变量以查找实际问题时,我不希望它显示在脚本的末尾 第一步是找到这个异常并处理它,对吗?我走不了那么远。以下是我得到的:Exception 不可修补异常(PowerShell),exception,powershell,try-catch,Exception,Powershell,Try Catch,我有可靠生成异常的代码。这是预期的,所以当我转储$error变量以查找实际问题时,我不希望它显示在脚本的末尾 第一步是找到这个异常并处理它,对吗?我走不了那么远。以下是我得到的: Function Add-PowerShellSnapIn($SnapInName){ Try{ if ((Get-PSSnapin -Name $SnapInName) -eq $null){ Write-Warning "SnapIn Is Not Already L
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"
如果我运行这段代码,我可以看到异常,但是我从来没有看到我的小“Write Warning”测试消息来指示Catch块捕获了异常。我一定是遗漏了什么。我看到的例外情况如下:
Get-PSSnapin:未找到与模式“Microsoft.Exchange.Management.PowerShell.Admin”匹配的Windows PowerShell管理单元。请检查模式,然后重试该命令。
在C:\users\myuser\Desktop\Test.ps1:4 char:20
+如果((Get-PSSnapin),则应将
-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"
您应该将
-ErrorAction stop
添加到Get-PSSnapin
以进入Catch块
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"