Powershell ItemNotFoundException在当前目录之外的文件上调用从管道中删除项

Powershell ItemNotFoundException在当前目录之外的文件上调用从管道中删除项,powershell,Powershell,假设我想从多个目录中删除以下文件 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

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

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中的一个bug,还是我没有正确使用它?是否有不同的指定方式递归删除文件,并进行管道过滤

其他说明:

  • 包含
    -WhatIf
    参数不会影响此处的问题;它只是强制
    Remove Item
    打印输出,而不是删除我的测试文件
  • 我不能只是将
    -Recurse
    传递给
    删除项
    ,因为在我的实际代码中,我正在对管道进行非平凡的筛选,以选择要删除的文件
  • 这是Windows 8.1上的Powershell v4.0

不使用foreach对象,您只需使用:

$files | Remove-Item  -WhatIf 
$files返回以下类型的对象:

如果您运行:

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

$files | foreach { Remove-Item -Path $_.FullName -WhatIf }