powershell中的奇数格式转换为[日期时间]

问题描述:

我正在写东西来获取某个程序的安装日期,但我似乎无法将返回的数字转换为奇怪的日期格式(yyyyMMdd)。我试过把它转换成[datetime],但是它返回下面的错误。powershell中的奇数格式转换为[日期时间]

这可能是一个简单的解决方法,但这是我还没有遇到的问题。有人可以帮忙吗?

在此先感谢!

$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 
+0

你勉强打我吧!但出于好奇,为什么要传递$ null而不是定义CultureInfo? –

+1

$ null表示当前文化(来自doc:“如果提供程序为null,则使用与当前文化相对应的CultureInfo对象。” –

+1

进一步查看MSDN,它看起来不是默认值,它将其设置为默认值不变的, –

你需要解析日期变种能够使用不变的CultureInfo和自定义格式:

$DateTimeVariable = [DateTime]::ParseExact("20160628", "yyyyMMdd", System.Globalization.CultureInfo]::InvariantCulture) 

$DateTimeVariable = [DateTime]::ParseExact($test.installdate, "yyyyMMdd", System.Globalization.CultureInfo]::InvariantCulture)