Skip to content

Instantly share code, notes, and snippets.

@anvanvan
Created November 17, 2023 05:50
Show Gist options
  • Save anvanvan/5c3497af27e4e427b262665c62d758df to your computer and use it in GitHub Desktop.
Save anvanvan/5c3497af27e4e427b262665c62d758df to your computer and use it in GitHub Desktop.
This PowerShell script recursively sorts image and video files in a specified folder by their creation date or media date, placing them into new directories named after the year and month of their creation or media date.
param(
[Parameter(Mandatory=$true)]
[string]$FolderPath
)
function Sort-Files {
Get-ChildItem -Path $FolderPath -File -Recurse | ForEach-Object {
#Write-Host "File: $_"
$creationDate = $_.CreationTime -replace("[^0-9/\:\sapm]")
$fileName = $_.Name
$extension = $_.Extension
#Write-Host $extension
$attrName = 'unkown'
If ('.png', '.jpg', '.jpeg', '.tif', '.tiff' -Contains $extension) {
$attrName = "Date taken"
}
If ('.mp4', '.avi', '.mpeg', '.3gp', '.mov', '.wmv' -Contains $extension) {
$attrName = "Media created"
}
$path = $_.FullName
$shell = New-Object -COMObject Shell.Application;
$folder = Split-Path $path;
$file = Split-Path $path -Leaf;
$shellfolder = $shell.Namespace($folder);
$shellfile = $shellfolder.ParseName($file);
$a = 0..500 | % { Process { $x = '{0} = {1}' -f $_, $shellfolder.GetDetailsOf($null, $_); If ( $x.split("=")[1].Trim() ) { $x } } };
#Write-Host $a
[int]$num = $a | % { Process { If ($_ -like "*$attrName*") { $_.Split("=")[0].trim() } } };
$mCreated = $shellfolder.GetDetailsOf($shellfile, $num);
$mDate = $mCreated -replace("[^0-9/\:\sapm]") #remove hidden characters
#Write-Host $mDate;
try {
$mediaDate = [DateTime]::ParseExact($mDate, "dd/MM/yyyy h:mm tt", $null)
$yearFolder = Join-Path $FolderPath -ChildPath $mediaDate.Year.ToString()
$monthFolder = Join-Path $yearFolder -ChildPath $mediaDate.Month.ToString()
New-Item -ItemType Directory -Path $monthFolder -Force | Out-Null
$newFilePath = Join-Path $monthFolder -ChildPath $fileName
Copy-Item -Path $path -Destination $newFilePath -Force
Write-Host "Copy $fileName to $($mediaDate.Year) \ $($mediaDate.Month)"
}
catch {
Write-Host "No media date"
#Write-Host $creationDate
$mediaDate = [DateTime]::ParseExact($creationDate, "dd/MM/yyyy h:mm:ss tt", $null)
$yearFolder = Join-Path $FolderPath -ChildPath $mediaDate.Year.ToString()
$monthFolder = Join-Path $yearFolder -ChildPath $mediaDate.Month.ToString()
New-Item -ItemType Directory -Path $monthFolder -Force | Out-Null
$newFilePath = Join-Path $monthFolder -ChildPath $fileName
Copy-Item -Path $path -Destination $newFilePath -Force
Write-Host "Copy $fileName to $($mediaDate.Year) \ $($mediaDate.Month)"
}
}
}
Sort-Files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment