PowerShell 2.0 and how to handle exceptions ?

Posted by Primoz on Stack Overflow See other posts from Stack Overflow or by Primoz
Published on 2011-01-14T14:06:49Z Indexed on 2011/01/14 14:53 UTC
Read the original article Hit count: 297

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!

© Stack Overflow or respective owner

Related posts about powershell

Related posts about exception-handling