I have captured “4/21/2015 9:56:44 AM” from a text file and stored it in a string variable ($myContent).
I now want to convert this into DateTime data type. Here is my code
[string]$myContent = Get-Content C:\MyFile.txt
[datetime]::ParseExact($myContent,”MM/dd/yyyy h:mm:ss”,$null) #This throws an error “String was not recognized as a valid DateTime”#
Can someone help me understand what is going wrong and suggest some solution here?
Hi Don, I tried the way you mentioned. Hope what you mentioned is as how it is in Line 4 (correct me if I am wrong.)
Line 1. [datetime]$whichDate = Read-Host “Enter date in MM/DD/YYYY format”
Line 2. [datetime]$myDate = ($whichDate).AddDays(-1)
Line 3. $myContent = Get-EventLog -LogName System -Message “Kernel-Boot” -After $myDate -Newest 1 -OutVariable Var |select TimeGenerated |ft -HideTableHeaders
Line 4. [datetime]$myTime = $myContent
Below is the error PS throws:
Cannot convert the “System.Object” value of type “System.Object” to type “System.DateTime”.
At line:1 char:1
Thank you all. Below code worked for me, the obstetrical I had was to convert String to datetime.
If you see in Line 3 even though I am eliminating Header and reading the date, the variable $myContent is storing some extra characters and thus when I try to convert, it throws an error. However I passed $myContent variable data into a text file and then read the content of text file into a separate variable $myVar and then applied datatype conversion on $myVar, which worked out here.
I am sure there would be much easy approaches, however this worked for me and unblocked me. Once again thank you all for your responses and support.
Line 1. [datetime]$whichDate = get-date
Line 2. [datetime]$myDate = ([datetime]$whichDate).AddDays(-1)
Line 3. $myContent = Get-EventLog -LogName System -Message “Kernel-Boot” -After $myDate -Newest 1 |select TimeGenerated |ft -HideTableHeaders
Line 4. $myContent |Out-File C:\MyFile.txt
Line 5. $myVar = Get-Content C:\MyFile.txt
Line 6. [datetime]$myTime = [datetime]::Parse(“$myVar”)