Skip to main content
 首页 » 编程设计

powershell之ItemNotFoundException 从当前目录之外的文件的管道中调用 Remove-Item

2024年12月31日10leader

假设我想从多个目录中删除以下文件。

PS d:\path> $files = gci -path . -Recurse -File 
 
PS d:\path> $files 
d:\path\foo.txt 
d:\path\sub\bar.txt 

我用 foreach调用 Remove-Item .
PS d:\path> $files | foreach { Remove-Item -Path $_ -WhatIf } 
What if: Performing the operation "Remove File" on target "D:\path\foo.txt". 
Remove-Item : Cannot find path 'D:\path\bar.txt' because it does not exist. 
At line:1 char:19 
+ $files | foreach { Remove-Item -Path $_ -WhatIf } 
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo          : ObjectNotFound: (D:\path\bar.txt:String) [Remove-Item], ItemNotFoundException 
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand 

似乎当传递文件的递归列表时, Remove-Item总是尝试从当前目录中删除文件。它可以删除 d:\path\foo.txt 正好。但是尝试删除 会引发错误d:\path\bar.txt ,因为没有这样的文件。它应该删除的文件位于 d:\path\sub\bar.txt .

请注意,以下代码工作正常,大概是因为 Get-ChildItem不是递归的。
PS D:\path> del .\sub\bar.txt -WhatIf 
What if: Performing the operation "Remove File" on target "D:\path\sub\bar.txt". 
 
PS D:\path> gci .\sub\bar.txt | % { del $_ -WhatIf } 
What if: Performing the operation "Remove File" on target "D:\path\sub\bar.txt". 

这是 PowerShell 中的错误,还是我没有正确使用它?是否有不同的规定方法来递归删除文件,受管道过滤的影响?

其他注意事项:
  • 包括-WhatIf参数不影响这里的问题;它只是强制Remove-Item打印输出而不是删除我的测试文件。
  • 我不能只是通过-RecurseRemove-Item因为在我的实际代码中,我正在对管道进行非平凡的过滤以选择要删除的文件。
  • 这是 Windows 8.1 上的 Powershell v4.0
  • 请您参考如下方法:

    您可以不使用 foreach-object,而是使用:

    $files | Remove-Item  -WhatIf  
    

    $files 返回类型为: System.IO.FileSystemInfo 的对象

    如果你运行:
    help Remove-Item -Parameter path 
    

    您将看到 path 参数接受一个字符串数组。 $files[0].gettype()不是字符串,因此必须进行某种类型转换