Search code examples
powershelltry-catchblock

PowerShell try/catch/finally


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?


Solution

  • -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]
    }