Skip to content

Instantly share code, notes, and snippets.

@CoolGoose
Last active June 8, 2023 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CoolGoose/75462ff5cfd6355153f4526746e09e2b to your computer and use it in GitHub Desktop.
Save CoolGoose/75462ff5cfd6355153f4526746e09e2b to your computer and use it in GitHub Desktop.
Move your camera roll pictures in folders, i've liked year / year-month with month having leading 0 (originally at https://www.thomasmaurer.ch/2015/03/move-files-to-folder-sorted-by-year-and-month-with-powershell/)
$TagLib = "C:\Program Files\PackageManagement\NuGet\Packages\TagLibSharp.2.2.0\lib\netstandard2.0\TagLibSharp.dll"
Add-Type -Path $TagLib
[System.Reflection.Assembly]::LoadFile($TagLib)
# Get the files which should be moved, without folders
$files = Get-ChildItem 'X:\Tmp\moveit' -Recurse | Where-Object { !$_.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 = 'X:\OneDrive\Photos'
foreach ($file in $files) {
$tag = [TagLib.File]::Create($file.FullName)
# Get year and Month of the file
if ($tag.ImageTag.DateTime) {
$year = $tag.ImageTag.DateTime.Year.ToString()
# add 0 prefix to month
$month = $tag.ImageTag.DateTime.Month.ToString("00")
}
elseif ($tag.Tag.DateTime) {
$year = $tag.Tag.DateTime.Year.ToString()
# add 0 prefix to month
$month = $tag.Tag.DateTime.Month.ToString("00")
}
else {
# 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()
# add 0 prefix to month
$month = $file.LastWriteTime.Month.ToString("00")
}
# Set Directory Path , change as wanted
$Directory = $targetPath + "\" + $year + "\" + $year + "-" + $month
# Create directory if it doesn't exists
if (!(Test-Path $Directory)) {
New-Item $directory -type directory
}
$MovedFileName = $file.Name
$MovedTargetDir = $Directory + "\" + $MovedFileName
$num = 1;
while(Test-Path -Path $MovedTargetDir)
{
$MovedFileName = $file.BaseName + "_$num" + $file.Extension
$MovedTargetDir = $Directory + "\" + $MovedFileName
$num+=1
}
# Out FileName, year and month
$file.Name
$MovedFileName
$year
$month
# Move File to new location, remove -Force if you might have files with the same name, i've used it since i knew that duplicates are ok to overwrite
$file | Move-Item -Destination $MovedTargetDir -Force
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment