Convert String to Date

Hi powershell gurus,

I am getting the data in the following format :

CLASS COUNT DESCRIPTION INITIAL_UPDATE LAST_UPDATE SEVERITY


Maintenance 1 IML Cleared (System Administrator) 07/02/2013 00:19 07/02/2013 00:19 Informational
Power 1 System Power Supply: General Failure (Power Supply 1) 09/05/2015 03:17 09/05/2015 21:20 Repaired
Power 1 System Power Supplies Not Redundant 09/05/2015 03:17 09/05/2015 21:20 Repaired
Power 1 System Power Supply: General Failure (Power Supply 2) 11/07/2015 03:39 11/07/2015 21:32 Repaired
Power 1 System Power Supplies Not Redundant 11/07/2015 03:39 11/07/2015 21:32 Repaired

Requirement is to have events picked only in the last 24hours from INITIAL_UPDATE. Any assistance is much appreciated.

Hi Manish,
Can you provide some more detail on this data? How are you getting it? Is it read from a text file? Is it generated by another command? It is data a collection of objects or an array of strings? I could make some assumptions based on how the data looks, but it would be just that, assumptions. If it’s an object, then it is very possible that the property is already in datetime. If it’s a string, you may be able to convert it to day time by simply type casting the string as datatime

IE.

[datetime]'7/14/1979 11:24:23'

then you can use a timespan to check how old the stamp is

New-TimeSpan -start ([datetime]'7/14/1979 11:24:23') -End (Get-Date)

#Results
@'
Days              : 13479
Hours             : 11
Minutes           : 56
Seconds           : 50
Milliseconds      : 81
Ticks             : 11646286100815366
TotalDays         : 13479.4978018696
TotalHours        : 323507.947244871
TotalMinutes      : 19410476.8346923
TotalSeconds      : 1164628610.08154
TotalMilliseconds : 1164628610081.54
'@

You can then use the timespan with an if statement to check if it’s within your desired range.

One slight problem.

The string has to be in US format - MM/DD/YYYY - if you use that approach.

US format
PS> [datetime]‘12/25/2016’

25 December 2016 00:00:00

UK format
PS> [datetime]‘25/12/2016’
Cannot convert value “25/12/2016” to type “System.DateTime”. Error: “String was not recognized as a
valid DateTime.”
At line:1 char:1

  • [datetime]‘25/12/2016’
  •   + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider
    
    

Converting a string to a DateTime object can be easy (if in US format) or a lot of work if in another format

What date format are you using?