ParseExact 和 TryParseExact 方法不接受 powershell 脚本中的多种日期格式

ParseExact and TryParseExact methods are not accepting the multiple dateformats in powershell script

我有不同类型的日期格式,如 MM/d/yyyyMM/dd/yyyy 等。我想在 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))

当我执行上面的行时,我遇到了以下异常

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

我想将字符串值解析为日期时间,并且该字符串可以是任何格式。 谁能告诉我如何使用 PowerShell 实现这一目标。 提前致谢。

此代码有效,尽管我没有找到一种方法使其适用于 DateTime.ParseExact() 的特定重载。

[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"

$result = $null
$format.ForEach({ [DateTime] $dt = New-Object DateTime; if([datetime]::TryParseExact($dateString, $_, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref] $dt)) { $result = $dt } });

Write-Host ($result)

输出:

11/8/2017 2:40:31 PM