Powershell - compare time in log file

Fox'sTail 21 Reputation points
2021-03-22T09:40:32.69+00:00

Hello everyone, can you help me with this question? I need to compare two strings with time. I have a log file that contents information looks like that: 22.03.2021 18:59:16.111 | some information.... I need to get frome there only information about time and compare it with time is now. So I have a script:

$MD = get-date - format "HH:MM:s"
     $path = some path to log file 
    $a = get-content -path $path -tail 1
     $b = $a.SubString(11,8)

Then i need to use if statements as I think:

If (($MD).AddHours(-0,5) -gt $b) {do something} 
    else {do anotherthing}

But it will not works because $mb and $b is a string data :( how I can compare it?

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-03-22T11:53:31.037+00:00

    Hi,

    PowerShell converts $b into a datetime object automatically. Actaully it's (get-date).AddHours(-0,5) -gt [datetime]$b. You can also try

    ([datetime]$MD).AddHours(-0.5) -gt [datetime]$b  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-03-23T02:08:28.703+00:00

    See if this makes more sense:

    $a = '1234567890112:10:139876'  # contains log file date data
    $MD = (Get-Date).AddHours(-0.5)
    $b = get-date $a.Substring(11,8)    # assumes that time is in 24 hour format (no AM/PM necessary)
    
    if ($MD -gt $b){
        "{0:HH:MM.s} > {1:HH:MM.s}" -f $MD, $b
    }
    else{
        "{0:HH:MM.s} <= {1:HH:MM.s}" -f $MD, $b
    }
    

    It's better if you don't treat date/time as strings. That almost always leads to grief. Get the information into a DateTime object and your comparisons will make a lot more sense.

    1 person found this answer helpful.

  2. Fox'sTail 21 Reputation points
    2021-03-22T09:56:30.153+00:00

    Miracle...
    If change

    If ((get-date).AddHours(-0,5) -gt $b)
    

    All is works... but still can't understand how it works if $b looks like a string data oO?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.