Windows – How to sort files into folders, according to file names – Windows CMD

command linepowershellshell-scriptwindows

How do I sort files into folders, according to file names, using CMD / PowerShell commands?

Let's say I have a folder containing a large amount of files (more than 20,000 files), where all the files have the same naming convention, e.g: (notice the pattern)

t_1001_1801.png
t_1001_1802.png
t_1001_1803.png
...
t_1001_2112.png (last file starts with 't_1001_')
t_1002_1801.png
t_1002_1802.png
t_1002_1803.png
....
t_1002_2112.png
t_1003_1801.png
t_1003_1802.png
t_1003_1803.png
...
t_1214_2112.png (last file in folder)

I run this CMD command to create a list of folders:
for /l %i in (1001,1,1214) do md x%i
which creates a list of folders, e.g:

x1001
x1002
x1003
...
x1214

Now I would like to sort (move) the files into the folders according to the files name, e.g:

- move the files t_1001_1801.png to t_1001_2112.png to the folder x1001.
- move the files t_1002_1801.png to t_1002_2112.png to the folder x1002.
...

Can I use shell commands for this purpose?

Best Answer

  • You simply need to split the FileName, get the number (like 1001), compare the number to the folders, get the correct folder and move the files in there:

    # Folder where Files and Folders are located
    $TopFolder = "C:\Install"
    
    # Getting Folders and Files
    $Folders = gci $TopFolder -OutVariable Files | ? { $_.PSisContainer }
    
    # Loop over all Files with *.png extension
    $Files | ? { $_.Extension -eq '.png' } | % {
    
        # Split FileName to get the number (like 1001)
        $num = ($_.Name -split "_")[1]
    
        # Get FolderName by reading out foldername (without 'x') and compare it to number
        $MoveTo = $Folders | ? { $_.Name.substring(1,($_.Name.length -1)) -eq $num }
    
        # If a folder was found, move file there. else print error
        if ($MoveTo)
        {
            Move-Item $_.FullName $MoveTo -Force
            Write-Host "Copied File $($_.Name) to $MoveTo"
        }
        else 
        { 
            Write-Host "Did not find folder x$($num) in $TopFolder" 
        }
    }
    
  • Related Question