Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell 2.0 and how to handle exceptions?

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!

like image 708
Primoz Avatar asked Jan 14 '11 14:01

Primoz


People also ask

How do you handle exceptions in PowerShell?

The way exception handling works in PowerShell (and many other languages) is that you first try a section of code and if it throws an error, you can catch it. Here is a quick sample. The catch script only runs if there's a terminating error. If the try executes correctly, then it skips over the catch .

How do I catch exceptions in PowerShell script?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

How do you handle specific exceptions?

In general, it's good programming practice to catch a specific type of exception rather than use a basic catch statement. When an exception occurs, it is passed up the stack and each catch block is given the opportunity to handle it. The order of catch statements is important.

How do you ignore an error in PowerShell and let it continue?

If there are special commands you want to ignore you can use -erroraction 'silentlycontinue' which will basically ignore all error messages generated by that command. You can also use the Ignore value (in PowerShell 3+): Unlike SilentlyContinue, Ignore does not add the error message to the $Error automatic variable.


1 Answers

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 :)"
}
like image 67
Roman Kuzmin Avatar answered Oct 30 '22 10:10

Roman Kuzmin