Modify Date Taken values on Photos with PowerShell, the Update-ExifDateTaken script cmdlet

(Part 3 of 3)    Download Script Here

The last two posts (Part 1, Part 2) have described the rationale behind creating these Exif cmdlets and looked at how to read Exif information from image files.  This final part looks at the Update-ExifDateTaken script cmdlet which will modify Exif meta-data contained within photo (.jpg) files.

See the examples in Part 1 for some ways you can use these script cmdlets.

Scott-Hanselman-Style DISCLAIMER: You Do Backup Your Photos Don’t You?  I am not a .Net programmer.  I have not be paid to program anything but PowerShell since around 1987 (seriously, I’m old) and .Net didn’t exist then.  The last non-PowerShell program I was actually paid to write was written in IBM System/370 Assembler.  No one taught me about .Net programming, I only know about it through PowerShell and MSDN and Bruce Payette.  I’ve used this script without any problems on literally thousands of photos.  I’m not saying don’t use it – just use it on a COPY of your precious images.

So, first up, because the script modifies files it must support the “-WhatIf” parameter.  There are two new parameters Update-ExifDateTaken version of the script: “-Offset”, which allows us to change the Exif Date Taken value by a specified amount; and “-PassThru”, which will pass the PathInfo objects along the pipeline.

(Note that Get-ExifDateTaken always passes on the PathInfo objects with the additional  Exif DateTaken [datetime] attribute; there would be no point in running the script if the output was not passed on because it otherwise has no side-effects.  In this Update version the output is optional because just updating the Exif data might be all that is needed.   If you want the output in the pipeline, specify –PassThru and you’ll get PathInfo objects decorated with additional ExifDateTaken and ExifOriginalDateTaken attributes).

The Process{} block structure is similar to the Get-ExifDateTaken script, but now there’s an extra step; once the script has the DateTaken value it updates it by adding the specified offset and replaces the value in the image file.

Pertinent points here are that to avoid file locking problems the script creates a MemoryStream object and saves the modified image data to the MemoryStream; it can then close the original input file and overwrite it (‘in-place’) by re-opening the file with a filemode of ‘Create’.   Note that this part of the code is protected by the ‘If ($PSCmdlet.ShouldProcess(…))’ test that supports the –WhatIf and –Confirm common parameters.

If the –PassThru switch parameter is the script outputs the current file’s PathInfo object along with two added attributes: the ExifDateTaken [datetime] object which reflects the modified DateTaken value; and the ExifOriginalDateTaken [datetime] object, in case that might be needed later in the pipeline.

That wraps it up.  The full download is available on SkyDrive here.  Finally, here’s the full script listing, including both the Get- and Update- variants of the script cmdlet:

ExifDateTime.ps1
<#Chris Warwick, @cjwarwickps, August 2013
chrisjwarwick.wordpress.comRevision: Now support PowerShell version 2.0 and above.This version published on SkyDrive here:
https://skydrive.live.com/redir?resid=7CB58BE453F7E567!1289&authkey=!ANY88H3ABytkigkThe script file contains two functions:

Get-ExifDateTaken -Path [filepaths]

Takes a file (fileinfo or string) or an array of these
Gets the ExifDT value (EXIF Property 36867)

Update-ExifDateTaken -Path [filepaths] -Offset [TimeSpan]

Takes a file (fileinfo or string) or an array of these
Modifies the ExifDT value (EXIF Property 36867) as specified

# Further samples:

# Just Update

gci *.jpg|Update-ExifDateTaken -Offset ‘-0:07:10’ -PassThru|ft Path, ExifDateTaken

# Update & Rename

gci *.jpg|
Update-ExifDateTaken -Offset ‘-0:07:10’ -PassThru|
Rename-Item -NewName {“LeJog 2011 {0:MM-dd HH.mm.ss dddd} ({1}).jpg” -f $_.ExifDateTaken, (Split-Path (Split-Path $_) -Leaf)}

# Just Rename

gci *.jpg|
Get-ExifDateTaken |
Rename-Item -NewName {“LeJog 2011 {0:MM-dd HH.mm.ss dddd} ({1}).jpg” -f $_.ExifDateTaken, (Split-Path (Split-Path $_) -Leaf)}

#>

#Requires -Version 2.0

Function Get-ExifDateTaken {
<#
.Synopsis
Gets the DateTaken EXIF property in an image file.
.DESCRIPTION
This script cmdlet reads the EXIF DateTaken property in an image and passes is down the pipeline
attached to the PathInfo item of the image file.
.PARAMETER Path
The image file or files to process.
.EXAMPLE
Get-ExifDateTaken img3.jpg
(Reads the img3.jpg file and returns the im3.jpg PathInfo item with the EXIF DateTaken attached)
.EXAMPLE
Get-ExifDateTaken *3.jpg |ft path, exifdatetaken
(Output the EXIF DateTaken values for all matching files in the current folder)
.EXAMPLE
gci *.jpeg,*.jpg|Get-ExifDateTaken
(Read multiple files from the pipeline)
.EXAMPLE
gci *.jpg|Get-ExifDateTaken|Rename-Item -NewName {“LeJog 2011 {0:MM-dd HH.mm.ss}.jpg” -f $_.ExifDateTaken}
(Gets the EXIF DateTaken on multiple files and renames the files based on the time)
.OUTPUTS
The scripcmdlet outputs PathInfo objects with an additional ExifDateTaken
property that can be used for later processing.
.FUNCTIONALITY
Gets the EXIF DateTaken image property on a specified image file.
#>

[CmdletBinding()]

Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias(‘FullName’, ‘FileName’)]
$Path
)

Begin
{
Set-StrictMode -Version Latest
If ($PSVersionTable.PSVersion.Major -lt 3) {
Add-Type -AssemblyName “System.Drawing”
}
}

Process
{
# Cater for arrays of filenames and wild-cards by using Resolve-Path
Write-Verbose “Processing input item ‘$Path‘”

$PathItems=Resolve-Path $Path -ErrorAction SilentlyContinue -ErrorVariable ResolveError
If ($ResolveError) {
Write-Warning “Bad path ‘$Path‘ ($($ResolveError[0].CategoryInfo.Category))”
}

Foreach ($PathItem in $PathItems) {
# Read the current file and extract the Exif DateTaken property

$ImageFile=(Get-ChildItem $PathItem.Path).FullName

Try {
$FileStream=New-Object System.IO.FileStream($ImageFile,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::Read,
1024,     # Buffer size
[System.IO.FileOptions]::SequentialScan
)
$Img=[System.Drawing.Imaging.Metafile]::FromStream($FileStream)
$ExifDT=$Img.GetPropertyItem(‘36867’)
}
Catch{
Write-Warning “Check $ImageFile is a valid image file ($_)”
If ($Img) {$Img.Dispose()}
If ($FileStream) {$FileStream.Close()}
Break
}
# Convert the raw Exif data

Try {
$ExifDtString=[System.Text.Encoding]::ASCII.GetString($ExifDT.Value)

# Convert the result to a [DateTime]
# Note: This looks like a string, but it has a trailing zero (0x00) character that
# confuses ParseExact unless we include the zero in the ParseExact pattern….

$OldTime=[datetime]::ParseExact($ExifDtString,“yyyy:MM:dd HH:mm:ss`0”,$Null)
}
Catch {
Write-Warning “Problem reading Exif DateTaken string in $ImageFile ($_)”
Break
}
Finally {
If ($Img) {$Img.Dispose()}
If ($FileStream) {$FileStream.Close()}
}

Write-Verbose “Extracted EXIF infomation from $ImageFile
Write-Verbose “Original Time is $($OldTime.ToString(‘F’))

# Decorate the path object with the EXIF dates and pass it on…

$PathItem | Add-Member -MemberType NoteProperty -Name ExifDateTaken -Value $OldTime -PassThru

} # End Foreach Path

} # End Process Block

End
{
# There is no end processing…
}

} # End Function

# ——————————————————————————————————

Function Update-ExifDateTaken {
<#
.Synopsis
Changes the DateTaken EXIF property in an image file.
.DESCRIPTION
This script cmdlet updates the EXIF DateTaken property in an image by adding an offset to the
existing DateTime value.  The offset (which must be able to be interpreted as a [TimeSpan] type)
can be positive or negative – moving the DateTaken value to a later or earlier time, respectively.
This can be useful (for example) to correct times where the camera clock was wrong for some reason –
perhaps because of timezones; or to synchronise photo times from different cameras.
.PARAMETER Path
The image file or files to process.
.PARAMETER Offset
The time offset by which the EXIF DateTaken value should be adjusted.
Offset can be positive or negative and must be convertible to a [TimeSpan] type.
.PARAMETER PassThru
Switch parameter, if specified the paths of the image files processed are written to the pipeline.
The PathInfo objects are additionally decorated with the Old and New EXIF DateTaken values.
.EXAMPLE
Update-ExifDateTaken img3.jpg -Offset 0:10:0  -WhatIf
(Update the img3.jpg file, adding 10 minutes to the DateTaken property)
.EXAMPLE
Update-ExifDateTaken *3.jpg -Offset -0:01:30 -Passthru|ft path, exifdatetaken
(Subtract 1 Minute 30 Seconds from the DateTaken value on all matching files in the current folder)
.EXAMPLE
gci *.jpeg,*.jpg|Update-ExifDateTaken -Offset 0:05:00
(Update multiple files from the pipeline)
.EXAMPLE
gci *.jpg|Update-ExifDateTaken -Offset 0:5:0 -PassThru|Rename-Item -NewName {“LeJog 2011 {0:MM-dd HH.mm.ss}.jpg” -f $_.ExifDateTaken}
(Updates the EXIF DateTaken on multiple files and renames the files based on the new time)
.OUTPUTS
If -PassThru is specified, the scripcmdlet outputs PathInfo objects with additional ExifDateTaken
and ExifOriginalDateTaken properties that can be used for later processing.
.NOTES
This scriptcmdlet will overwrite files without warning – take backups first…
.FUNCTIONALITY
Modifies the EXIF DateTaken image property on a specified image file.
#>

[CmdletBinding(SupportsShouldProcess=$True)]

Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias(‘FullName’, ‘FileName’)]
$Path,

[Parameter(Mandatory=$True)]
[TimeSpan]$Offset,

[Switch]$PassThru
)

Begin
{
Set-StrictMode -Version Latest
If ($PSVersionTable.PSVersion.Major -lt 3) {
Add-Type -AssemblyName “System.Drawing”
}

}

Process
{
# Cater for arrays of filenames and wild-cards by using Resolve-Path
Write-Verbose “Processing input item ‘$Path‘”

$PathItems=Resolve-Path $Path -ErrorAction SilentlyContinue -ErrorVariable ResolveError
If ($ResolveError) {
Write-Warning “Bad path ‘$Path‘ ($($ResolveError[0].CategoryInfo.Category))”
}

Foreach ($PathItem in $PathItems) {
# Read the current file and extract the Exif DateTaken property

$ImageFile=(Get-ChildItem $PathItem.Path).FullName

Try {
$FileStream=New-Object System.IO.FileStream($ImageFile,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::Read,
1024,     # Buffer size
[System.IO.FileOptions]::SequentialScan
)
$Img=[System.Drawing.Imaging.Metafile]::FromStream($FileStream)
$ExifDT=$Img.GetPropertyItem(‘36867’)
}
Catch{
Write-Warning “Check $ImageFile is a valid image file ($_)”
If ($Img) {$Img.Dispose()}
If ($FileStream) {$FileStream.Close()}
Break
}
#region Convert the raw Exif data and modify the time

Try {
$ExifDtString=[System.Text.Encoding]::ASCII.GetString($ExifDT.Value)

# Convert the result to a [DateTime]
# Note: This looks like a string, but it has a trailing zero (0x00) character that
# confuses ParseExact unless we include the zero in the ParseExact pattern….

$OldTime=[datetime]::ParseExact($ExifDtString,“yyyy:MM:dd HH:mm:ss`0”,$Null)
}
Catch {
Write-Warning “Problem reading Exif DateTaken string in $ImageFile ($_)”
# Only continue if an absolute time was specified…
#Todo: Add an absolute parameter and a parameter-set
# If ($Absolute) {Continue} Else {Break}
$Img.Dispose();
$FileStream.Close()
Break
}

Write-Verbose “Extracted EXIF infomation from $ImageFile
Write-Verbose “Original Time is $($OldTime.ToString(‘F’))

Try {
# Convert the time by adding the offset
$NewTime=$OldTime.Add($Offset)
}
Catch {
Write-Warning “Problem with time offset $Offset ($_)”
$Img.Dispose()
$FileStream.Close()
Break
}

# Convert to a string, changing slashes back to colons in the date.  Include trailing 0x00…
$ExifTime=$NewTime.ToString(“yyyy:MM:dd HH:mm:ss`0”)

Write-Verbose “New Time is $($NewTime.ToString(‘F’)) (Exif: $ExifTime)”

#endregion

# Overwrite the EXIF DateTime property in the image and set
$ExifDT.Value=[Byte[]][System.Text.Encoding]::ASCII.GetBytes($ExifTime)
$Img.SetPropertyItem($ExifDT)

# Create a memory stream to save the modified image…
$MemoryStream=New-Object System.IO.MemoryStream

Try {
# Save to the memory stream then close the original objects
# Save as type $Img.RawFormat  (Usually [System.Drawing.Imaging.ImageFormat]::JPEG)
$Img.Save($MemoryStream, $Img.RawFormat)
}
Catch {
Write-Warning “Problem modifying image $ImageFile ($_)”
$MemoryStream.Close(); $MemoryStream.Dispose()
Break
}
Finally {
$Img.Dispose()
$FileStream.Close()
}

# Update the file (Open with Create mode will truncate the file)

If ($PSCmdlet.ShouldProcess($ImageFile,‘Update EXIF DateTaken’)) {
Try {
$Writer = New-Object System.IO.FileStream($ImageFile, [System.IO.FileMode]::Create)
$MemoryStream.WriteTo($Writer)
}
Catch {
Write-Warning “Problem saving to $OutFile ($_)”
Break
}
Finally {
If ($Writer) {$Writer.Flush(); $Writer.Close()}
$MemoryStream.Close(); $MemoryStream.Dispose()
}
}
# Finally, if requested, decorate the path object with the EXIF dates and pass it on…

If ($PassThru) {
$PathItem |
Add-Member -MemberType NoteProperty -Name ExifDateTaken -Value $NewTime -PassThru |
Add-Member -MemberType NoteProperty -Name ExifOriginalDateTaken -Value $OldTime -PassThru
}

} # End Foreach Path

} # End Process Block

End
{
# There is no end processing…
}

} # End Function

The Get-ExifDateTaken PowerShell Script Cmdlet

(Part 2 of 3) (Part 1) (Part 3)

{Updated: 08/2013}

The last blog post described how to update a whole bunch of photos using two script cmdlets called Get-ExifDateTaken and Update-ExifDateTaken.   This post describes the first of these script cmdlets in more detail.

There are several Windows APIs (Wia, GDI etc) that can read Exif values from image files.  I tend to avoid using COM if there’s a .Net alternative, so I used the [System.Drawing.Imaging.Metafile] class and its associated GetPropertyItem() method to read the Exif data I needed.

The script needs to handle pipeline input, so the first thing to do is to get the script Param() statement coded correctly:

[CmdletBinding()]Param (
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True)
]
[Alias(‘FullName’, ‘$FileName’)]
$Path
)

This allows image file names to be passed in as normal parameters or to be read from the pipeline using various aliases if needed.

The script cmdlet’s Process{} block needs to accept multiple file names, arrays of names, wildcards and so on.  This is all handled with a call to the Resolve-Path cmdlet and we iterate over the results in a foreach:

Process
{
# Cater for arrays of filenames and wild-cards by using Resolve-Path
Write-Verbose “Processing input item ‘$Path'”$PathItems=Resolve-Path $Path -ErrorAction SilentlyContinue -ErrorVariable ResolveError
If ($ResolveError) {
Write-Warning “Bad path ‘$Path’ ($($ResolveError[0].CategoryInfo.Category))”
}    Foreach ($PathItem in $PathItems) {
# Read the current file and extract the Exif DateTaken property# (……SNIP…)} # End Foreach Path} # End Process Block

Within the loop we open each image file into a FileStream (this is quicker than using the $Img.FromFile(…) method) and get the Exif DateTaken value by using GetPropertyItem(‘36867’) – Exif property 36867 is DateTaken; just love those magic numbers…

The value is converted to a [DateTime] and passed down the pipeline attached to the PathInfo object that we got from Resolve-Path.  Passing rich objects in this way (rather than just outputting the DateTaken value on its own, for example) ensures that stages further down the pipeline have access to all the information they might need.

Note that in the code snippet here the error checking code has been removed for clarity – see the full listing in the last post for the complete source:

$ImageFile=$PathItem.Path$FileStream=New-Object System.IO.FileStream($ImageFile,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::Read,
1024,     # Buffer size
[System.IO.FileOptions]::SequentialScan
)
$Img=[System.Drawing.Imaging.Metafile]::FromStream($FileStream)
$ExifDT=$Img.GetPropertyItem(‘36867’)# Convert the raw Exif data$ExifDtString=[System.Text.Encoding]::ASCII.GetString($ExifDT.Value)# Convert the result to a [DateTime]
# Note: This looks like a string, but it has a trailing zero (0x00)
# character that confuses ParseExact unless we include the zero
# in the ParseExact pattern….$OldTime=[datetime]::ParseExact($ExifDtString,“yyyy:MM:dd HH:mm:ss`0”,$Null)

$FileStream.Close(); $Img.Dispose()

Write-Verbose “Extracted EXIF infomation from $ImageFile”
Write-Verbose “Original Time is $($OldTime.ToString(‘F’))”

# Decorate the path object with the EXIF dates and pass it on…

$PathItem | Add-Member -MemberType NoteProperty -Name ExifDateTaken -Value $OldTime
Write-Output $PathItem

Note how easily PowerShell enable calls to .Net methods – a great feature of  PowerShell.

The final part will look at updating Exif dates and included the full code for the Get-ExifDateTaken and Update-ExifDateTaken cmdlets.

Reading and Changing Exif Photo Times with PowerShell

(Part 1 of 3) (Part 2) (Part 3)

{Updated: 08/2013}

Back in 2011 I went off with a bunch of like-minded folk on a long-distance cycle (see, for example, here).  We all had a great time, but with six separate cameras in use we came back with a whole load of photos that needed sorting out.

We wanted to combine all the photos from the trip into a single consolidated collection, but apart from renaming all the image files it was also going to be necessary to change the times (the Date Taken values) so the photos all appeared in the correct order when viewed.

Rather than trying to accurately synchronise the times on all of cameras, we used a simple trick of simultaneously pointing them all at a scene and taking a common image; this would allow us to later correct the times of each image to at least the nearest second.  (See below for the actual photos!)

The obvious question is then how to actually change the times and rename the files?  Well, there are countless photo programs (e.g. Windows Live Photo Gallery, Picassa, etc, etc) that would do this, but for batch updates it’s a lot easier to use PowerShell.

Here’s how to rename the files:

$FormStr=”LeJog 2011 {0:MM-dd HH.mm.ss dddd} ({1}).jpg”
gci *.jpg | Get-ExifDateTaken | Ren -New {$FormStr -f $_.ExifDateTaken,(Split-Path (Split-Path $_) -Leaf)}

There are a couple of things to notice here…. Firstly, the new file name is specified in a scriptblock, this returns a dynamically calculated file name based on the original PathInfo item that was passed to the Rename cmdlet (in the $_ variable) and the time the photo was taken (passed in $_.ExifDateTaken).

The PowerShell format operator (-f) combines the template string, in the $FormStr variable, with the values necessary to calculate the new name. In this case, the photos from each camera were held in a folder named for the camera’s owner (so my photos were all in ..\Chris\img001.jpg … etc); so ‘Split-Path (Split-Path $_) –Leaf’ just returns the parent folder names – in this case, ‘Chris’, ‘David’, ‘Mick’, ‘Mike’ or ‘Andy’ [name plugs].

The date-time part of the name just uses standard DateTime format strings, so the resulting renamed image might be something like:

“LeJog 2011 07-10 14.27.21 Sunday (Chris).jpg”

…the important point here is that you can create any name you want; you might not like my choice of filename (although it is at least sortable!) but flexibility is unlimited here.

The other thing to notice is the Get-ExifDateTaken cmdlet.  The source for this, along with the  companion Update-ExifDateTaken cmdlet will be published in a the next two blog entries (Part 2) (Part 3).

The example above shows how to rename a bunch of image files.  To actually change the Date Taken value needs a different approach.  Photos store meta-data such as the Date Taken value as Exif information which is actually combined with the image data within the image file, so the image file must be opened and saved to modify the Date Taken Exif value.  The Update-ExifDateTaken script cmdlet does this:

gci *.jpg | Update-ExifDateTaken -Offset ‘-0:07:10’ -PassThru | ft Path, ExifDateTaken

Here, we specify the amount of time the Date Taken value on each image file should be changed by.  In the example the offset is negative, so any Date Taken values will be moved forwards to earlier times (presumably this particular camera’s clock was too fast).

Note that this technique can also be useful if you go across time zones and forget to change your camera’s clock…

Finally, here’s an example that shows how to modify the Exif Date Taken meta-data and rename the image file in the same command:

$FormStr=”LeJog 2011 {0:MM-dd HH.mm.ss dddd} ({1}).jpg”
gci *.jpg | Update-ExifDateTaken -Offset ‘-0:07:10’ -PassThru |
Ren -New {$FormStr -f $_.ExifDateTaken,(Split-Path (Split-Path $_) -Leaf)}

The Get-ExifDateTaken and the Update-ExifDateTaken script cmdlets were written with input from James O’Neill’s session at the 2011 European PowerShell Deep Dive event in Frankfurt; James has written-up the session in a blog here: “Maximize the reuse of your PowerShell”.

The script cmdlets will be published in the follow-up blog entries: (Part 2) (Part 3)

Oh, and the image we used to sync the camera times?  Here’s one of our tireless support drivers, Andy, holding up the lunchtime sausage:

LeJog 2011 07-06 14.13.54 Wednesday (Andy) LeJog 2011 07-06 14.13.54 Wednesday (Chris) LeJog 2011 07-06 14.13.54 Wednesday (David)
LeJog 2011 07-06 14.13.54 Wednesday (Mick) (2) LeJog 2011 07-06 14.13.54 Wednesday (Mick) LeJog 2011 07-06 14.13.54 Wednesday (Mike)