Powershell: IOException try/catch isn't working

Try/catch statements can only catch terminating errors (these usually indicate a severe error). PowerShell also has the concept of non-terminating errors. The file-in-use error you see is a non-terminating error. This is good from the perspective that if you were moving thousands of files and one had its target in use, the command doesn't crap out it keeps going. You have two choices here. You can ignore these errors by setting the ErrorAction parameter to SilentlyContinue (value of 0) e.g.:

Move-Item foo bar -ErrorAction SilentlyContinue

Or you can convert the non-terminating error to a terminating error by setting this same parameter to 'Stop' and then use the try/catch although don't filter by IOException because PowerShell wraps the exception e.g.:

try { Move-Item .\About_This_Site.txt vmmap.exe -ErrorAction Stop } `
catch {$_.GetType().FullName}
System.Management.Automation.ErrorRecord

I was able to solve this by adding -ErrorAction Stop to the Move-Item command. That seems to force it to throw an error as intended, instead of doing whatever it wants.

Tags:

Powershell