1

I'm writing something to get the installation date for a certain program, but I can't seem to convert the number that is returned into a weird date format (yyyyMMdd). I've tried casting it to [datetime], but that returns the error below.

This may be an easy fix, but it's something I haven't run across yet. Can someone please help?

Thanks in advance!

$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`

2 Answers 2

2

Given your date "20160628" Try:

[datetime]::ParseExact($Date,"yyyyMMdd",$null)

and you get:

Tuesday, June 28, 2016 12:00:00 AM
Sign up to request clarification or add additional context in comments.

4 Comments

You barely beat me to it! But out of curiosity, why pass $null instead of defining a CultureInfo?
$null means current culture (from the doc: "If provider is null, the CultureInfo object that corresponds to the current culture is used."
Looking at MSDN further, it appears None is the default, behind the scenes it sets it to Invariant as well.
indeed, I guess it's a faster way than entering [System.Globalization.CultureInfo]::InvariantCulture :)
2

You'll need to parse the date to a variable using invariant cultureInfo and a custom format:

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

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.