Written by 5:27 pm Microsoft, Microsoft Azure, PowerShell, Windows, Windows Server • 42 Comments

PowerShell: Sort and Move Files by Date to month and year

PowerShell Sort and move files by date month year

This quick blog post, shows, how you can sort and move files to folder sorted by date (year and month) with PowerShell. I had to sort a lot of files and put them into folders for each month and year. So for example when the files was created/modified in February 2012, the file had to be moved into the folder 2012 and the subfolder 2 (for February). For this, I created this quick and dirty script. This script gives you an example of how you can sort and move files by date using PowerShel.

# Get the files which should be moved, without folders
$files = Get-ChildItem 'C:\Users\Thomas\OneDrive\OneDrive Camera Roll' -Recurse | where {!$_.PsIsContainer}
 
# List Files which will be moved
$files
 
# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'C:\Users\Thomas\OneDrive\pictures\Albums'
 
foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()
 
# Out FileName, year and month
$file.Name
$year
$month
 
# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
 
# Move File to new location
$file | Move-Item -Destination $Directory
}

Please as always if you use a PowerShell script from the internet, test it first before you run it against your production environment. This script can for example also be very handy to sort documents, pictures or Windows Logfiles.

I hope this blog post helps you to sort and move files by date using PowerShell. If you have any questions, let me know in the comments below.

Tags: , , , , , , , , , , , , Last modified: March 26, 2020
Close Search Window
Close