I am trying to parse a file for only the most recent entries. Each entry in the log file starts with date in the format "m/d/yyyy h:mm:ss PM".
I write a script that accomplishes what I wanted but unfortunately this script runs on Powershell 5 but not Powershell 2
$regex = '\b([1-2][0-9]|[0-9])\/([1-3][0-9]|[0-9])\/(20[0-9][0-9]) ((1[0-2]|0?[1-9]):([0-5][0-9]):([0-5][0-9]) ([AaPp][Mm]))'
$lines = gci C:\temp\Gateway.log | select-string -pattern $regex |select linenumber, matches
$log=@()
foreach($line in $lines)
{
[datetime]$logdate = ($line.matches).value
$ln = $line.linenumber
if ($logdate -gt '2017-06-29 12:00:00')
{
$log += $ln
}
}
$log
When i try to run this script on the server with powershell 2, i get the following error.
Cannot convert null to type "System.DateTime".
I am having trouble converting the value found by the select-string into datetime. tried convert to string with tostring and also with out-string
$dt = $line.matches
$val = $dt|select Value
$val1 = $val|Out-String
$val2 = $val.tostring()
[datetime]$val1
[datetime]$val2
How can I get the value as datetime so I can do datemath on in it powershell 2?
DateTimeis poor form because it assumes the locale actually accepts date/time values of that specific format. Use something like[DateTime]::ParseExact($val1, "M/d/yyyy H:mm:ss tt", [CultureInfo]::InvariantCulture)instead. (I forget if there's a more PowerShellian way of doing that.)14/68/3016 1:62:63 PMas a valid date/time, just let the parser sort out that's invalid. Things like[0-9]+are fine for simple delineation work. If the date/time happens to have a fixed size or a non-space delimiter it's even simpler.Hdenotes a 24 hour format, change to lower caseh