Removing extra files from a second folder?

Soldato
Joined
6 Nov 2002
Posts
9,939
Location
London UK
Hi all,

My scenario is I have two folders containing matching files of different types, however the second folder has many extra files which aren't needed.

E.g.

Folder A
filename01.abc
filename03.abc
filename04.abc
filename08.abc
filename10.abc

Folder B
filename01.xyz
filename02.zxz
filename03.xyz
filename04.xyz
filename05.xyz
filename06.xyz
filename07.xyz

filename08.xyz
filename09.xyz
filename10.xyz

Is there a quick and easy way to remove the extra files from the second folder (i.e. filename02.xyz, filename05.xyz......)?

I have thousands of files to sort through so need an automated method.

Thanks :)
 
If I've understood correctly this should do it.

Copy this into the 'Powershell ISE'
Edit the $PathOne and $PathTwo variables to reflect your paths.
Hit F5 to run.

It should create a folder in 'Folder B' called 'ToRemove' and put the extra files in there so you can check them before deletion.

If you want me to clarify what it's doing and how, let me know and I'll try and answer but to be honest it should be fairly easy to work out from the code.

PLEASE TEST on a small subset first, copy them elsewhere if needed. I've tested it quickly here while writing it and it shouldn't be destructive but as a disclaimer, run at own risk etc.

If you don't have powershell then install it, learn it, love it. Or alternatively I could knock up a CMD batch instead but I'm slowly losing those skills now I've moved over to PS.

Code:
$PathOne = 'C:\Scripts\Folder A'
$PathTwo = 'C:\Scripts\Folder B'

If (-not (Test-Path $PathTwo\ToRemove) ) 
{
    mkdir $PathTwo\ToRemove
}

Get-ChildItem $PathTwo | `
    foreach `
    {
        $BaseName = $_.BaseName

        If (-not (Test-Path $PathOne\$BaseName.*) ) `
        {

            Move-Item -Path $PathTwo\$BaseName.* -Destination $PathTwo\ToRemove
        }
    }
 
You Sir are a star! Works perfectly, many thanks indeed.
Or alternatively I could knock up a CMD batch instead but I'm slowly losing those skills now I've moved over to PS.
Understand you there, 15 years ago this sort of scripting used to be my day job, can't do it for toffee now! :p
 
Back
Top Bottom