Powershell:IOException try/catch 不起作用 [英] Powershell: IOException try/catch isn't working

查看:84
本文介绍了Powershell:IOException try/catch 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:该进程无法访问该文件,因为它正被另一个进程使用.[Move-Item], IOException +fullyQualifiedErrorId : MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

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

我尝试了以下 try/catch 块,但它仍然在同一移动项目"行上出错.对我在这里做错了什么有任何想法吗?

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
          }

谢谢.

推荐答案

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

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

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

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

这篇关于Powershell:IOException try/catch 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆