I have been trying to write a Powershell script based on some code online that will read the metadata info from picture, video and other files and then sort them based on one of the dates (date taken currently seems to be the best bet if it's available, but date modified works on files that have not yet been altered).
However, when I run the script and pull the info, I can't convert the string to a date. Here's roughly how I get the info through a COM object:
PS C:/> $objShell = New-Object -ComObject Shell.Application
PS C:/> $objFolder = $objShell.namespace("C:MyFolder")
PS C:/> $date = $objFolder.GetDetailsOf($objFolder.Items().Item(0), 12)
PS C:/> $date
7/?10/?2014 ??7:09 PM
The problem is I should be able to convert this to a datetime object. For instance, if I manually write it in it works:
PS C:/> [datetime]::ParseExact("7/10/2014 7:09 PM","g",$null)
Thursday, July 10, 2014 7:09:00 PM
But if I substitute the variable it doesn't work:
PS C:/> [datetime]::ParseExact($date,"g",$null)
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:1 char:1
+ [datetime]::ParseExact($date,"g",$null)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
This is most likely due to the fact that the variable isn't actually what I'm seeing. It's in fact longer. Not to mention the fact that if you iterate through all the characters, you can see where the extra length is coming from:
PS C:> $date.Length #should be about 16, you'd think
22
PS C:> $datearray = @()
PS C:> for ($i = 0; $i -lt $date.Length; $i++) {$datearray += $date[$i]}
PS C:> $datearray #i'm printing on one line and in quotes for ease of viewing
" 7/ 10/ 2014 7:09 PM"
If you try printing the array with a join or something similar, the results are (to me, without knowing what's going on) unpredictable. It treats it like it has 22 characters, but prints ignoring the spaces.
I'm sure I could spend a bit of time and do some string formatting, but I'd rather just be able to parse the given date. What's going on?
Edit: I'm able to access the file info easily, though I prefer not to. I'm mainly focusing on why the results I'm seeing are inconstant and showing a length that doesn't match how it prints out, and how I can deal with them. If nothing else, I'm curious as to what is going on.
See Question&Answers more detail:
os