I have different types of date formats like MM/d/yyyy
, MM/dd/yyyy
etc.. I want to parse the different formats of string value to datetime in PowerShell.
[string[]]$format = @("MM/d/yyyy hh:mm:ss tt","M/d/yyyy hh:mm:ss tt","MM/dd/yyyy hh:mm:ss tt","M/dd/yyyy hh:mm:ss tt")
$dateString = "11/8/2017 02:40:31 PM"
Write-Host ([datetime]::ParseExact($dateString, $format, $null))
when I'm executing above lines I'm getting below exception
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:5 char:1
+ Write-Host ([datetime]::ParseExact($dateString, $format, $null))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
I want to parse string value to datetime and the string is can be in any format. Can anyone tell me how to achieve this using PowerShell. Thanks in advance.