How to sort files into folders, according to file names - Windows CMD
Solution 1:
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"
}
}
Solution 2:
The following batch
- Changes to the folder to start in
- iterates with a for command through all *.png file
- uses a for /f to split the name at the underscores into tokens and uses the
2nd3rd one to - check if a subfolder x with the number exists, if not it is created
- finally moves the file to the subfolder.
:: Q:\Test\2018\06\03\SU_1328200.cmd
@Echo off
PushD "C:\Users\UserName\Pictures\"
For %%A in (t_*_*_*.png) do For /F "tokens=3delims=_" %%B in ("%%A") Do (
If Not exist "x%%B" MD "x%%B"
Move "%%A" "x%%B"
)
PopD
Sample tree /F after running the batch
(outdated from first requirement with 2nd token)
> tree /F
├───x1001
│ t_1001_1801.png
│ t_1001_1802.png
│ t_1001_1803.png
│ t_1001_2112.png
│
├───x1002
│ t_1002_1801.png
│ t_1002_1802.png
│ t_1002_1803.png
│ t_1002_2112.png
│
├───x1003
│ t_1003_1801.png
│ t_1003_1802.png
│ t_1003_1803.png
│
└───x1214
t_1214_2112.png
A PowerShell script:
## Q:\Test\2018\06\03\SU_1328200.ps1
PushD "C:\Users\UserName\Pictures\"
Get-ChildItem t_*_*_*.png |
Where BaseName -match 't_\d{2}_(\d{4})_\d{4}'|
Group {'x'+$Matches[1]}|
ForEach{MD $_.Name;$_.Group|Move -Dest $_.Name}