Last active
September 20, 2020 15:55
-
-
Save timiles/a4db1e09062548174073f0b3034935ed to your computer and use it in GitHub Desktop.
PowerShell script to prefix files by DateTime from file name or Date Taken from EXIF data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-DateTakenFromExifData { | |
param([String] $filePath) | |
try { | |
$imgData = New-Object System.Drawing.Bitmap($filePath) | |
try { | |
[Byte[]]$dateTakenExifData = $imgData.GetPropertyItem(36867).Value | |
[String]$dateString = [System.Text.Encoding]::ASCII.GetString($dateTakenExifData) | |
return [DateTime]::ParseExact($dateString, "yyyy:MM:dd HH:mm:ss`0", $null) | |
} | |
finally { | |
$imgData.Dispose() | |
} | |
} | |
catch { } | |
return $null | |
} | |
function Get-DateFromFileName { | |
param([String] $fileName) | |
if ($fileName -match '\d{8}') { | |
return [DateTime]::ParseExact($Matches[0], "yyyyMMdd", [Globalization.CultureInfo]::CreateSpecificCulture('en-GB')) | |
} | |
} | |
function Get-DateTimeFromFileName { | |
param([String] $fileName) | |
if ($fileName -match '\d{8}_\d{6}') { | |
return [DateTime]::ParseExact($Matches[0], "yyyyMMdd_HHmmss", [Globalization.CultureInfo]::CreateSpecificCulture('en-GB')) | |
} | |
} | |
function Get-DateTimeForFilePrefix { | |
param([System.IO.FileInfo] $fileInfo) | |
$date = Get-DateTimeFromFileName ($fileInfo.Name) | |
if ($date) { | |
return $date | |
} | |
$date = Get-DateFromFileName ($fileInfo.Name) | |
if ($date) { | |
return $date | |
} | |
$date = Get-DateTakenFromExifData ($fileInfo.FullPath) | |
if ($date) { | |
return $date | |
} | |
return $fileInfo.LastWriteTime | |
} | |
Get-ChildItem | ForEach-Object { | |
$from = $_.Name | |
$dateTimeForPrefix = Get-DateTimeForFilePrefix $_ | |
$to = "$($dateTimeForPrefix.ToString('yyyy-MM-dd HH.mm.ss')) $from" | |
Write-Host "Renaming `"$from`" to `"$to`"" | |
Rename-Item $from $to | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment