我正在写一些东西来获取某个程序的安装日期,但我似乎无法将返回的数字转换为奇怪的日期格式(yyyyMMdd)。我试过将其转换为[datetime]
,但这会返回下面的错误。
这可能是一个简单的修复,但这是我还没有遇到的东西。有人能帮帮我吗?
提前感谢!
$test = Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq 'exampleProgram'} | select installdate
,
[datetime]$test.installdate
Cannot convert value "20160628" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:1
+ [datetime]$test.installdate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider`
给定你的日期"20160628"试一试:
[datetime]::ParseExact($Date,"yyyyMMdd",$null)
得到:
Tuesday, June 28, 2016 12:00:00 AM
您需要使用不变量cultureInfo和自定义格式将日期解析为变量:
$DateTimeVariable = [DateTime]::ParseExact("20160628", "yyyyMMdd", System.Globalization.CultureInfo]::InvariantCulture)
或
$DateTimeVariable = [DateTime]::ParseExact($test.installdate, "yyyyMMdd", System.Globalization.CultureInfo]::InvariantCulture)