[英]powershell - delete files using list of file names
I got the the following code from stack overflow and it works fine. 我从堆栈溢出中获得了以下代码,并且工作正常。
$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
}
Now I want to delete the files with file names on the list. 现在,我要删除列表中具有文件名的文件。 I tried some variations of the above such as replacing Exclude with Include but without success.
我尝试了上述方法的一些变体,例如用Include替换Exclude,但没有成功。 Can anyone help please?
有人可以帮忙吗?
$targetFolder = "D:\TEST_123"
$fileList = "D:\DeleteList.txt"
Get-ChildItem -Path "$targetFolder\*" -Recurse -Include @(Get-Content $fileList) | Remove-Item -Verbose
For -Include
to work you should specify \\*
at the end of a folder name and filename with extension in your deletion list. 为了使
-Include
起作用,您应该在删除列表的文件夹名称和文件名末尾指定\\*
。 The code above works for me, deleting only specified files in folder and all of its subfolders. 上面的代码对我有用,仅删除文件夹及其所有子文件夹中的指定文件。
I also used -Verbose
instead of foreach
and Write-Host
. 我还使用
-Verbose
代替了foreach
和Write-Host
。
To offer a simplification of n01d's helpful answer : 为了简化n01d的有用答案 :
You can use Remove-Item
directly: 您可以直接使用
Remove-Item
:
Remove-Item $TargetFolder\* -Recurse -Include (Get-Content List.txt) -Verbose
Note the required \\*
appended to $TargetFolder
. 注意
$TargetFolder
后面的必需\\*
。
-Include
and -Exclude
can be tricky (see this answer of mine), but -Include
should work here, as long as List.txt
contains mere filenames (no path components). -Include
和-Exclude
可能会非常棘手(见这个答案我的),但-Include
应该在这里工作,只要List.txt
包含单纯的文件名 (没有路径组件)。
As in n01d's answer, -Verbose
is meant to replace the explicit foreach
loop with the Write-Host
calls. 就像n01d的答案一样,
-Verbose
旨在用Write-Host
调用替换显式的foreach
循环。
Also note that Remove-Item
writes nothing to the output stream, so there's no reason to pipe it to Out-Null
还要注意,
Remove-Item
不会向输出流写入任何内容,因此没有理由将其通过管道传递给Out-Null
I find that the -Include
param really doesn't work the way you would expect, most of the time. 我发现
-Include
参数实际上在大多数情况下并没有像您期望的那样工作。
So I'd propose this code to simply get it working, fast. 因此,我建议使用此代码以使其快速运行。
$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
}
You could make it a bit faster if you'd like by screwing with -include
, but I frankly think it sucks, and this would work. 如果愿意,可以使用
-include
加快它的速度,但是我坦率地认为它很烂,而且可以。
You can try this : 您可以尝试以下方法:
Get-Content .\filesToDelete.txt | ForEach-Object {Remove-Item $_}
it's easier and pretty self explanatory ( $_
stands for the current variable of the for loop). 它更简单,更容易解释(
$_
代表for循环的当前变量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.