如何避免删除项PowerShell错误“进程无法访问文件”?

部署新版本之前,我们使用TfsDeployer和PowerShell脚本删除正在删除项目的文件夹。 有时PS脚本失败,出现错误

Remove-Item:无法删除项目Services \ bin:进程无法访问文件Services \ bin,因为它正在被另一个proc使用Get-ChildItem -Path $ Destination -Recurse | Remove-Item <<<< -force -recurse + CategoryInfo:WriteError:(C:\ Program Files \ Services \ bin:DirectoryInfo)[Remove-Item],IOException FullyQualifiedErrorId:RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

我试图按照强制删除PowerShell中的文件和目录的答案 有时失败,但并不总是pipeget-childitem -recurse到remove-item。

get-childitem * -include * .csv -recurse | 除去项目

,但是错误仍然是周期性发生的。 我们正在使用解锁器手动杀死locking应用程序,(通常是w3wp),但我更喜欢find自动化的解决scheme。

另一个(不理想的)选项是禁止powershell错误 get-childitem -recurse -force -erroraction静静地继续

任何build议,欢迎。

您可以检查Remove-Item cmdlet发出的错误。 使用Remote-Item上的ErrorVariable参数将其错误存储在variables中,然后遍历它,只显示所需的错误。

 Get-ChildItem * -Include *.csv -recurse | ForEach-Object { $removeErrors = @() $_ | Remove-Item -ErrorAction SilentlyContinue -ErrorVariable removeErrors $removeErrors | where-object { $_.Exception.Message -notlike '*it is being used by another process*' } } 

晚了,但有人可能会觉得这很有用。

在一个自动化脚本中,我通过进程找回任何正在使用我想要删除的目录的path,并杀死它们。

有时候其他应用程序可能会locking一个文件,所以我使用进程资源pipe理器来查找句柄/ DLL。 如果可以杀死应用程序,我将杀死添加到脚本。

然后删除目录。

  get-process | foreach{ $pName = $_ if ( $pName.Path -like ( $INSTALL_PATH + '*') ) { Stop-Process $pName.id -Force -ErrorAction SilentlyContinue } Remove-Item -Force -Recurse $INSTALL_PATH 

那么,因为它是一个locking文件的Web应用程序,为什么不在移除项目之前先执行iisreset /stop ,然后iisreset /start

正如其他人提到的,你可以防止IISlocking文件。 本博客文章介绍了如何使用PowerShell回收单个应用程序池。