tags:

views:

55

answers:

2

I have a PS script that kicks off every 5 minutes to check for newly dropped folders and move them. Problem is that sometimes items within the folder are still being written to, in which case the script errors with:

Move-Item : The process cannot access the file because it is being used by another process. [Move-Item], IOException + FullyQualifiedErrorId : MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

I've tried the following try/catch block but it still errors on the same "Move-Item" line. Any thoughts to what I'm doing wrong here?

          try {
           Move-Item -Force "$fileString" $fileStringFixed
          }
          catch [System.IO.IOException] {
           return
          }

Thank you.

A: 

Try catching system.exception in case the io exception is being wrapped

Gary
Same error still: catch [System.Exception] { return }
orbitron
+3  A: 

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 -ea 0

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 -ea stop } `
catch {$_.GetType().FullName}
System.Management.Automation.ErrorRecord
Keith Hill
That looks like it did it, thank you so much!
orbitron
Or globally set it to stop: $ErrorActionPreference = 'Stop'
dangph