gpt4 book ai didi

Powershell:IOException try/catch 不起作用

转载 作者:行者123 更新时间:2023-12-02 11:25:57 25 4
gpt4 key购买 nike

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

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 block ,但在同一“Move-Item”行上仍然出错。对我在这里做错了什么有什么想法吗?

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

谢谢。

最佳答案

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

Move-Item foo bar -ErrorAction SilentlyContinue

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

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

关于Powershell:IOException try/catch 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com