We help IT Professionals succeed at work.

Try / Catch error during Powershell script

Sybux asked

I'm running this little script :

      get-Stat -Entity $myHosts
trap [VimException]
      Write-Error "fails"

I want to trap the error from get-stat but it's never catch.
Here is the output of the script :

Get-Stat : 14.03.2012 21:07:39    Get-Stat        Object reference not set to a
n instance of an object.
At C:\vCheck6\test.ps1:3 char:10
+     get-Stat <<<<  -Entity $myHosts
    + CategoryInfo          : NotSpecified: (:) [Get-Stat], VimException
    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomatio

Any ideas are welcome !
Watch Question

Hi your , problem is that it is generating a non terminating error

here is an example of how to trap them

$ErrorActionPreference = "Stop"

    copy-item "c:\notexists\file.txt" "c:\temp" 
catch {

write-host "bad copy"


Open in new window

The key is Line1   ,
this can be reverted by issuing
$ErrorActionPreference = "Continue"