假设我想从多个目录中删除以下文件。
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
打印输出而不是删除我的测试文件。 -Recurse
至 Remove-Item
因为在我的实际代码中,我正在对管道进行非平凡的过滤以选择要删除的文件。 请您参考如下方法:
您可以不使用 foreach-object,而是使用:
$files | Remove-Item -WhatIf
$files 返回类型为:
System.IO.FileSystemInfo
的对象
如果你运行:
help Remove-Item -Parameter path
您将看到 path 参数接受一个字符串数组。
$files[0].gettype()
不是字符串,因此必须进行某种类型转换