[英]powershell - delete files using list of file names
我从堆栈溢出中获得了以下代码,并且工作正常。
$TargetFolder = “Pathofyourfolder”
$Files = Get-ChildItem $TargetFolder -Exclude (gc List.txt) -Recurse
foreach ($File in $Files)
{
write-host “Deleting File $File” -foregroundcolor “Red”;
Remove-Item $File | out-null
}
现在,我要删除列表中具有文件名的文件。 我尝试了上述方法的一些变体,例如用Include替换Exclude,但没有成功。 有人可以帮忙吗?
$targetFolder = "D:\TEST_123"
$fileList = "D:\DeleteList.txt"
Get-ChildItem -Path "$targetFolder\*" -Recurse -Include @(Get-Content $fileList) | Remove-Item -Verbose
为了使-Include
起作用,您应该在删除列表的文件夹名称和文件名末尾指定\\*
。 上面的代码对我有用,仅删除文件夹及其所有子文件夹中的指定文件。
我还使用-Verbose
代替了foreach
和Write-Host
。
为了简化n01d的有用答案 :
您可以直接使用Remove-Item
:
Remove-Item $TargetFolder\* -Recurse -Include (Get-Content List.txt) -Verbose
注意$TargetFolder
后面的必需\\*
。
-Include
和-Exclude
可能会非常棘手(见这个答案我的),但-Include
应该在这里工作,只要List.txt
包含单纯的文件名 (没有路径组件)。
就像n01d的答案一样, -Verbose
旨在用Write-Host
调用替换显式的foreach
循环。
还要注意, Remove-Item
不会向输出流写入任何内容,因此没有理由将其通过管道传递给Out-Null
我发现-Include
参数实际上在大多数情况下并没有像您期望的那样工作。
因此,我建议使用此代码以使其快速运行。
$TargetFolder = “Pathofyourfolder”
$Files = Get-ChildItem $TargetFolder -Recurse| Where Name -in (gc List.txt)
foreach ($File in $Files)
{
write-host “Deleting File $File” -foregroundcolor “Red”;
Remove-Item $File | out-null
}
如果愿意,可以使用-include
加快它的速度,但是我坦率地认为它很烂,而且可以。
您可以尝试以下方法:
Get-Content .\filesToDelete.txt | ForEach-Object {Remove-Item $_}
它更简单,更容易解释( $_
代表for循环的当前变量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.