Script that separates files according to destination folder name

cunhaigo23

New Member
Greetings, I need a Script that separates files According to destination folder name. Example if in the destination folder there is a folder named Paulo, it searches in the source folder where the files are located to separate files that have the name Paulo.

Origin

Paulo24567.mp4

Destiny

Paulo folder

Thank you very much
 

Josephur

Windows Forum Admin
Staff member
Premium Supporter
Microsoft Certified Professional
Does not work on subfolders, but this one liner should do the trick.

for /D %G in ("*") DO move %~nxG* %~nxG
 

Neemobeer

Application and Cloud Security Engineer
Staff member
Powershell version. Supports sub directories on the source and can handle duplicate names on destination.

Code:
$SourceDirectory = ".\SOURCE"
$DestinationDirectory = ".\DEST"

$Directories = Get-ChildItem -Path $DestinationDirectory -Directory
$Files = Get-ChildItem -Path $SourceDirectory -File -Recurse
foreach($Dir in $Directories) {
    foreach($File in $Files) {
        if($File.Name -like "*$($Dir.Name)*") {
            if(Test-Path "$($Dir.FullName)\$($File.Name)") {
                $Items = Get-ChildItem -Path "$($Dir.FullName)" -File
                if($Items) {
                    $NewFileName = "$($File.Name.Split('.')[0])$($Items.Count)$($File.Extension)"
                    Move-Item -Path "$($File.FullName)" -Destination "$($Dir.FullName)\$NewFileName"
                }
            } else {
                Move-Item -Path "$($File.FullName)" -Destination "$($Dir.FullName)"
            }       
        }
    }
}
 
Top