PowerShell try/catch/finally

steve picture steve · Jul 21, 2011 · Viewed 106.4k times · Source

I recently wrote a PowerShell script that works great - however, I'd like to now upgrade the script and add some error checking / handling - but I've been stumped at the first hurdle it seems. Why won't the following code work?

try {
  Remove-Item "C:\somenonexistentfolder\file.txt" -ErrorAction Stop
}

catch [System.Management.Automation.ItemNotFoundException] {
  "item not found"
}

catch {
  "any other undefined errors"
  $error[0]
}

finally {
  "Finished"
}

The error is caught in the second catch block - you can see the output from $error[0]. Obviously I would like to catch it in the first block. What am I missing?

Answer

Bruce picture Bruce · Jul 21, 2011

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}