0

I am trying to write a script to search for duplicate base file names with different extensions in subfolders under a path.

For example a folder may contain file1.zip and file1.pdf and I want to delete the PDFs only on the duplicates inside the folder.

I came with this which will will work only for the set path in the path variable. Adding -recurse to the Get-Child Item doesn't seem to work.

$Path = "C:\logs"

ForEach ($File in (Get-ChildItem $Path\*.pdf))
{   If ((Test-Path "$Path\$($File.Basename).zip"))
    {   $File | Remove-Item 
    }
}

Any suggestions on how to get this logic to apply to all subfolders?

1

Below is what you need. The problem you were having is that you weren't providing the correct path. Since you are using -Recurse, the path $Path\$($File.Basename).zip is not always correct, for it is correct only if the file is an immediate child of $Path.

$path = "C:\logs"
Get-ChildItem $path\*.pdf -Recurse | ForEach-Object {
    if( Test-Path "$($_.DirectoryName)\$($_.Basename).zip" ) {
        Remove-Item "$($_.DirectoryName)\$($_.Basename).pdf"
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.