PowerShell Function doesn't work consistently

Viewed 27

Here's my function:

Function Convert-StringDateTime {

<#
 Function extracts datetime object from a specificlly
 formatted string containing a date time in the format:
 M/dd/yyy h:mm tt
 Ex: 8/13/2010 1:17 AM
#>


  Param (
    [Parameter(Mandatory=$True)]
      [String] $FunctDteStr
  )

  $DateFmt = "M/dd/yyyy"
  $TimeFmt = "h:mm tt"
  
  $DTParts = $FunctDteStr -split(" ")
  $DateStr = $DTParts[0]
  $TimeStr = $DTParts[1] + " " + $DTParts[2]
  $DT = [DateTime]::ParseExact($DateStr,$DateFmt,$null)
  $TM = [DateTime]::ParseExact($TimeStr,$TimeFmt,$null)
  
  $CreationDateTime = $DT + $TM.TimeofDay
  
  Return ,$CreationDateTime

} #End Function Convert-StringDateTime

If I call it like this:

$CR = Convert-StringDateTime -FunctDteStr "8/13/2010 1:17 PM"

It runs fine and returns $CR as a datetime value.

PS> $CR

Friday, August 13, 2010 1:17:00 PM


However, if I call it using a variable which contains the same string...

PS>  $($MetaData[0].'Date Taken')
‎8/‎13/‎2010 ‏‎1:17 AM

PS> $CR = Convert-StringDateTime -FunctDteStr $($MetaData[0].'Date Taken')
Exception calling "ParseExact" with "3" argument(s): "String was not 
recognized as a valid DateTime."
At G:\BEKDocs\Scripts\Functions\Function - Convert-StringDateTime.ps1:22 char:3
+   $DT = [DateTime]::ParseExact($DateStr,$DateFmt,$null)
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException
 
Exception calling "ParseExact" with "3" argument(s): "String was not 
recognized as a valid DateTime."
At G:\BEKDocs\Scripts\Functions\Function - Convert-StringDateTime.ps1:23 char:3
+   $TM = [DateTime]::ParseExact($TimeStr,$TimeFmt,$null)
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException
 
The property 'TimeofDay' cannot be found on this object. Verify that the 
property exists.
At G:\BEKDocs\Scripts\Functions\Function - Convert-StringDateTime.ps1:25 char:3
+   $CreationDateTime = $DT + $TM.TimeofDay
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

It will also produce the errors if I use this syntax:

$CR = Convert-StringDateTime -FunctDteStr "$($MetaData[0].'Date Taken')"

Just for completeness:

PS>  $($MetaData[0].'Date Taken') | gm

   TypeName: System.String

I'm at a total loss...

0 Answers
Related