📎 AI Summary:
The thread discusses methods for moving files into destination folders based on matching folder names. The original poster seeks a script to automate this separation process, providing a specific example. Replies include a simple batch command that works without subfolder support and a PowerShell script that handles subdirectories and duplicate filenames, with the overall sentiment indicating practical solutions for organizing files efficiently.

cunhaigo23

New Member
Member details
Joined
Jul 7, 2021
Messages
1
Thread Author #1
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
 

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

Josephur

Windows Forum Admin
Staff member
Premium Supporter
Microsoft Certified Professional
Member details
Joined
Aug 3, 2010
Messages
1,283
Does not work on subfolders, but this one liner should do the trick.

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

Neemobeer

Windows Forum Team
Staff member
Member details
Joined
Jul 4, 2015
Messages
8,995
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)"
            }       
        }
    }
}
 

Solution