Bob Klimes
Bob Klimes

Reputation: 165

convert string to datetime in powershell 2.0

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?

Upvotes: 0

Views: 1541

Answers (1)

user6811411
user6811411

Reputation:

To my experience the am/pm conversion doesn't work (also not with [CultureInfo]::InvariantCulture) if your current locale settings don't apply with it.

You need to specify a cultureinfo object which supports am/pm

$enUS = 'en-US' -as [Globalization.CultureInfo]
$val1 = (get-date).ToString("M/d/yyyy H:mm:ss tt", $enUS)
$val1
[DateTime]::ParseExact($val1, "M/d/yyyy H:mm:ss tt", $enUS)

Upvotes: 1

Related Questions