Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
C Lamb Avatar asked Dec 03 '22 14:12

C Lamb


2 Answers

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

like image 175
n01d Avatar answered Dec 22 '22 00:12

n01d


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

like image 31
Oussama K Avatar answered Dec 22 '22 01:12

Oussama K