Powershell:IOException try/catch无效

orb*_*ron 14 powershell

我有一个PS脚本,每5分钟启动一次,检查新删除的文件夹并移动它们.问题是有时文件夹中的项目仍在写入,在这种情况下脚本错误:

Move-Item:进程无法访问该文件,因为它正由另一个进程使用.[Move-Item],IOException + FullyQualifiedErrorId:MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

我尝试了以下try/catch块,但它仍然在同一个"Move-Item"行上出错.对我在这里做错了什么的想法?

          try {
           Move-Item -Force "$fileString" $fileStringFixed
          }
          catch [System.IO.IOException] {
           return
          }
Run Code Online (Sandbox Code Playgroud)

谢谢.

Kei*_*ill 25

Try/catch语句只能捕获终止错误(这些通常表示严重错误).PowerShell还具有非终止错误的概念.您看到的文件使用中的错误是一个非终止错误.从这个角度来看,这是好的,如果你移动了数千个文件而且其中一个目标正在使用中,那么命令就不会让它继续下去.你有两个选择.您可以通过将ErrorAction参数设置为SilentlyContinue(值为0)来忽略这些错误,例如:

Move-Item foo bar -ea 0
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过将此相同参数设置为"Stop"将非终止错误转换为终止错误,然后使用try/catch但不过滤IOException,因为PowerShell包装了异常,例如:

try { move-Item .\About_This_Site.txt vmmap.exe -ea stop } `
catch {$_.GetType().FullName}
System.Management.Automation.ErrorRecord
Run Code Online (Sandbox Code Playgroud)

  • 或全局设置为停止:$ ErrorActionPreference ='停止' (5认同)

小智 6

我能够通过添加-ErrorAction StopMove-Item命令来解决这个问题。这似乎迫使它按预期抛出错误,而不是做任何想做的事情。