简体   繁体   中英

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. 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. 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 .

To offer a simplification of n01d's helpful answer :

You can use Remove-Item directly:

Remove-Item $TargetFolder\* -Recurse -Include (Get-Content List.txt) -Verbose

Note the required \\* appended to $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).

As in n01d's answer, -Verbose is meant to replace the explicit foreach loop with the Write-Host calls.

Also note that Remove-Item writes nothing to the output stream, so there's no reason to pipe it to Out-Null

I find that the -Include param really doesn't work the way you would expect, most of the time.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM