# Check multiple subdirectories and delete if file exists [closed]

Long story short, I have over 180K files that I need to delete. I have all of the file names that need to be deleted in a TXT file, however the files that need deleting are scattered in over 400 folders within this one directory.

I'm attempting to design a script that reads a .TXT file, checks if the file exists in any of the sub directories and deletes if found.

I'm quite knew to PowerShell / Object-oriented scripts so need some assistance.

$WorkingDir = 'D:\TEST\'$txtFile = Get-Content "D:\TEST\Files.txt"

#foreach file in the .TXT
foreach ($file in$txtFile){
# foreach file in the folders
foreach($dir in (Get-ChildItem$WorkingDir -Recurse)){
# if the file name is in directory listed, then delete?
If (Test-Path $file){ Remove-Item$file
}
}
}


Example of data in TXT file:

215865.wav
215864.wav
215875.wav
215887.wav
215885.wav
215884.wav
215902.wav
215906.wav


Attempted to run script above on some test data so it didn't have to scan through hundreds of folders...runs successfully but nothing gets deleted.

• Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you edit to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see help center) and the question may be deleted. Jul 9 '19 at 14:09
• Okay, I will read the help center. Thanks @Toby Jul 9 '19 at 14:10
• Editing posts to include suggestions that are given in answers creates an issue where the answers appear to not make sense. We call this "answer invalidation". Your edits have been rolled back, and the answer now makes more sense. Unfortunately your question was off-topic to start with. Now that you have working code, though, you may want to post a follow up question. See the same link above for how to do that. Jul 11 '19 at 11:41

• the array $txtfile is already in memory • iterating it and per entry searching recursivly the directories (the var$dir in fact also includes files) creates a lot of unneccessary overhead.
$WorkingDir = 'D:\TEST\'$txtFile = Get-Content "D:\TEST\Files.txt"
Get-ChildItem $WorkingDir -Recurse|ForEach-Object{ If ($txtFile -contains $_.Name){ Remove-Item$_.FullName -WhatIf

If the output looks OK, remove the trailing -WhatIf