Powershell trap [Exception] is not catching my error Powershell trap [Exception] is not catching my error powershell powershell

Powershell trap [Exception] is not catching my error


Try like this:

trap { write-host "file not found, skipping";continue;}$modtime = Get-ItemProperty c:\manoj -erroraction stop

Based on comments from OP:

I think you misunderstood what is being said in the article you have linked to:

In this example, we used continue to caused execution to return to the scope the trap is in and execute the next command. It’s important to note that execution only returns to the scope of the trap, so if the exception was thrown inside a function, or even inside a if statement, and trapped outside of it … the continue will pick up at the end of the nested scope.

So if you do something like this:

trap{ write-host $_; continue;}throw "blah"write-host after

after will be printed.

But if you do something like this:

trap{ write-host $_ ; continue}function fun($f) {      throw "blah"      write-host after}funwrite-host "outside after"

after will NOT be printed, but outside after will be.

Alternatively, use a try-catch block:

      try{      $modtime = (Get-ItemProperty $f -erroraction stop).LastWriteTime      write-host "if file not found then shouldn't see this"      }      catch{        write-host "file not found, skipping".      }


You have to set $ErrorActionPreference to SilentlyContinue inside of the function or outside of the script (for global application) for trap to work. Alternatively (as mentioned above), set -ErrorAction common parameter to the same thing.