Powershell script to Stamp pictures with Date/Time

Quick tip:

I hate having my pictures automatically named like IMG_0384.CR2, because during backups (moving around hard drives, cloud, etc) it happens that I lose the original date of the files. And although I group pictures in folders, it’s still sometimes easy to lost the original date.

So I just created (well, I copied from others but made some adjustments) this helpful Powershell script, which will stamp the filenames with the date when the picture was taken.

# Based on https://ss64.com/ps/syntax-stampme.html
# usage: PS C:\>./stampme.ps1 "F:\somepicture.png"
# usage: PS C:\> foreach ($file in get-ChildItem *.CR2) { ./stampme.ps1 $file.name }


#StampMe.ps1
param( [string] $fileName)

# Check the file exists
if (-not(Test-Path $fileName)) {break}

# Display the original name
"Original filename: $fileName"

$fileObj = get-item $fileName

# https://stackoverflow.com/questions/6834259/how-can-i-get-programmatic-access-to-the-date-taken-field-of-an-image-or-video
try {


  $pic = New-Object System.Drawing.Bitmap($fileName)
  $bitearr = $pic.GetPropertyItem(36867).Value 
  $string = [System.Text.Encoding]::ASCII.GetString($bitearr) 
  $DateTime = [datetime]::ParseExact($string,"yyyy:MM:dd HH:mm:ss`0",$Null)
}
catch 
{
  $DateTime =  (Get-Item $fileName).LastWriteTime
}

# Get the date
#$DateStamp = get-date -uformat "%Y-%m-%d_%H%M%S"
$DateStamp = $DateTime.ToString("yyyy-MM-dd_HHmmss")

$extOnly = $fileObj.extension

if ($extOnly.length -eq 0) {
   $nameOnly = $fileObj.Name
   rename-item "$fileObj" "$DateStamp-$nameOnly"
   }
else {
   $nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'')
   rename-item "$fileName" "$DateStamp-$nameOnly$extOnly"
   }

# Display the new name
"New filename: $DateStamp-$nameOnly$extOnly"

Look how my pictures were badly organized before:

And look how they are much more beautiful now:

Enjoy!

Much better, uh? :-)

comments powered by Disqus