PowerShell: Sort Files Into Folders Based on Filename

Print View Mobile View

After coming back from a trip recently, I imported all the photos from my camera to my computer by automatically renaming them using the Exif Data in the format Month-Day-Year-Filename (%m-%d-%Y-%f): 05_17_2018_DSC_5560.NEF. After editing the photos, each NEF file would also have a JPEG and a XMP file. While backing up these photos, I want each set of files in their own folder based on their date/month. We can get the date/month detail available in the file name. Now, to automatically sort files into folders based on filename, I am going to use a PowerShell script. End result would be something like this:
Sort Files Into Folders Based on Filename

PowerShell Script to Sort Files Into Folders Based on Filename

Get-ChildItem *_*_*_DSC_*.* |
  Where BaseName -match '(\d{2})_(\d{2})_\d{4}_DSC_\d{4}'|
    Group {$Matches[1]+'-'+$Matches[2]}|
      ForEach{MD $_.Name;$_.Group|Move -Dest $_.Name}

You can save this script in a .PS1 file for easily running in any folder you want.

Code breakdown:
Here, Get-ChildItem cmdlet will retrieve each file in the target folder matching the pattern: *_*_*_DSC_*.*. I am not specifying a particular file extension here as I want to move NEF, JPEG, and XMP files. If you are working with a single file type, that can be specified like this: *_*_*_DSC_*.NEF.

BaseName -match '(\d{2})_(\d{2})_\d{4}_DSC_\d{4}' helps us in matching pattern based on the filename. We are going to sort these files in month-date format, hence targeting (\d{2})_(\d{2}).

Group {$Matches[1]+'-'+$Matches[2]} names the folders based on the pattern we targeted above.

And finally, ForEach{MD $_.Name;$_.Group|Move -Dest $_.Name} runs a loop creating the directories and moving each of the matching file into their respective folder.

That’s all!

Hope this script helped in you in organizing your files. If you have any comments or query, please post them in the comment below.