Created
November 3, 2023 09:20
-
-
Save dhcgn/90c6677f2d6c5c70c123b050b9f9a310 to your computer and use it in GitHub Desktop.
Retrieves the date when a file was taken or created with Powershell
This file contains 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
<# | |
.SYNOPSIS | |
Retrieves the date when a file was taken or created. | |
.DESCRIPTION | |
The Get-DateTaken function uses the Windows Shell COM object to access file properties that aren't directly accessible through .NET's System.IO classes. It attempts to retrieve the "Date taken" property of the file. If this property is not available, it retrieves the "Date created" property instead. The retrieved date string is sanitized and parsed into a DateTime object. | |
.PARAMETER file | |
The file for which the date taken or created is to be retrieved. This parameter is mandatory. | |
.OUTPUTS | |
DateTime | |
Returns the date when the file was taken or created. | |
.EXAMPLE | |
PS C:\> Get-DateTaken -file $file | |
This command retrieves the date when the file represented by the $file variable was taken or created. | |
#> | |
function Get-DateTaken { | |
[OutputType([datetime])] | |
param ( | |
[Parameter(Mandatory = $true)] | |
[System.IO.FileInfo] | |
$file | |
) | |
# $DateFormat = 'dd.MM.yyyy HH:mm' | |
$DateTakenWinApi = 12 | |
$DateCreatedWinApi = 4 | |
if ($null -eq $Shell) { | |
$Shell = New-Object -ComObject shell.application | |
} | |
$dir = $Shell.Namespace($_.DirectoryName) | |
$DateTakenString = $dir.GetDetailsOf($dir.ParseName($_.Name), $DateTakenWinApi) | |
if ($DateTakenString -eq '') { | |
$DateTakenString = $dir.GetDetailsOf($dir.ParseName($_.Name), $DateCreatedWinApi) | |
} | |
# sanitze string | |
$DateTakenString = $DateTakenString -replace '[^0-9\.\:\ \/]', '' | |
# parse to DateTime | |
$DateTaken = Get-Date $DateTakenString # -Format $DateFormat | |
$DateTaken | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I try to run this on a jpg picture that has a date taken property set, I receive an error:
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "" to type "System.DateTime". Error: "String was not
recognized as a valid DateTime." I'm not sure why, the field appears fine to me: