PowerShell 2.0以及如何处理异常?

Pri*_*moz 7 powershell exception-handling powershell-2.0

为什么我在运行这两个简单样本时会在控制台上显示错误消息?我希望我得到"错误测试:)"打印在控制台上:

Get-WmiObject:RPC服务器不可用.(来自HRESULT的异常:0x800706BA)在行:3 char:15 + Get-WmiObject <<<< --ComputerName possible.nonexisting.domain.com -Credential(Get-Credential)-Class Win32_logicaldisk + CategoryInfo:InvalidOperation:(:) [ Get-WmiObject],COMException + FullyQualifiedErrorId:GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

要么

试图除以零.在行:3 char:13 + $ i = 1/<<<< 0
+ CategoryInfo:NotSpecified:(:) [],ParentContainsErrorRecordException + FullyQualifiedErrorId:RuntimeException

第一个例子:

try
{
    $i = 1/0   
    Write-Host $i     
}
catch [Exception]
{ 
    Write-Host "Error testing :)" 
}
Run Code Online (Sandbox Code Playgroud)

第二个例子:

try
{
    Get-WmiObject -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk 
}
catch [Exception]
{ 
    Write-Host "Error testing :)" 
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你!

Rom*_*min 12

第一个例子

错误发生在编译/解析时(PowerShell足够聪明),因此代码甚至不执行,实际上它无法捕获任何内容.请尝试使用此代码,您将捕获异常:

try
{
    $x = 0
    $i = 1/$x
    Write-Host $i
}
catch [Exception]
{
    Write-Host "Error testing :)"
}
Run Code Online (Sandbox Code Playgroud)

第二个例子

如果您设置$ErrorActionPreference = 'Stop'全局,那么您将按预期打印"错误测试:)".但是你$ErrorActionPreference可能是这样的'Continue':在这种情况下,没有终止错误/异常,你只需通过引擎将非终止错误消息打印到主机上.

$ErrorActionPreference您也可以使用Get-WmiObject参数来代替全局选项ErrorAction.尝试将其设置为Stop,您将捕获异常.

try
{
    Get-WmiObject -ErrorAction Stop -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk
}
catch [Exception]
{
    Write-Host "Error testing :)"
}
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用公共参数`-ErrorAction SilentlyContinue来抑制它,并使用公共参数`-ErrorVariable someVariableName`捕获错误,以便您可以测试它:`Get-WmiObject -ComputerName possible.nonexisting.domain.com -Credential( Get-Credential)-Class Win32_logicaldisk -ErrorAction SilentlyContinue -ErrorVariable noWMI; if($ NoWMI){Write-Host"错误测试:)"}` (4认同)