PowerShell 2.0 and how to handle exceptions?

此生再无相见时 提交于 2019-12-03 13:19:07

问题


Why I get error message printed on the console when running these two simple samples ? I want that I get "Error testing :)" printed on the console insted of:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:3 char:15 + Get-WmiObject <<<< -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

or

Attempted to divide by zero. At line:3 char:13 + $i = 1/ <<<< 0
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RuntimeException

First example:

try
{
    $i = 1/0   
    Write-Host $i     
}
catch [Exception]
{ 
    Write-Host "Error testing :)" 
}

Second example:

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

Thank you very much!


回答1:


First example

The error happens at compile/parsing time (PowerShell is clever enough), so that the code is not even executed and it cannot catch anything, indeed. Try this code instead and you will catch an exception:

try
{
    $x = 0
    $i = 1/$x
    Write-Host $i
}
catch [Exception]
{
    Write-Host "Error testing :)"
}

Second example

If you set $ErrorActionPreference = 'Stop' globally then you will get "Error testing :)" printed, as expected. But your $ErrorActionPreference is presumably 'Continue': in that case there is no terminating error/exception and you just get the non terminating error message printed to the host by the engine.

Instead of the global $ErrorActionPreference option you can also play with Get-WmiObject parameter ErrorAction. Try to set it to Stop and you will catch an exception.

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


来源:https://stackoverflow.com/questions/4691874/powershell-2-0-and-how-to-handle-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!