none
Using Select-String with Time Constraint RRS feed

  • Question

  • Hello,

    I'm writing a small little script to check all log files in a certain path for errors. Select-String is what I'm currently using to pattern search. I was curious what the easiest way to check only files that are 24 hours old in that file path? Thanks!


    Tuesday, February 21, 2017 4:35 PM

Answers

  • HI,

    you need to filter the files before you Select-String them:

    Get-ChildItem -Path $Path | Where-Object {$_.LastWriteTime -ge $date} | Select-String -Pattern "Error"

    After select-stringing them it's no longer a fileinfo, so it won't have a LastWriteTime anymore.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    Wednesday, February 22, 2017 3:11 PM

All replies

  • Use LastWriteTime to filter the results.


    \_(ツ)_/

    Tuesday, February 21, 2017 4:54 PM
  • We don't use string matching for dates and times in PowerShell. The LastWriteTime property of a file object is a DateTime object. You can use -le/-lt/-ge/-gt/-eq to compare DateTime objects. Get-Date returns the current date and time as a DateTime object.

    -- Bill Stewart [Bill_Stewart]

    Tuesday, February 21, 2017 5:03 PM
    Moderator
  • Hi Bill,

    Thanks for the useful info. This what the line of code I'm using looks like:

    Select-String -Pattern "Error" -Path "path_goes_here" | Where-Object {$_.LastWriteTime -ge $date}


    The dates of the files in the path directory are less than 24 hours old, and my $date variable is set to:

    $date = [DateTime]::Today.AddHours(-24)

    Yet when I execute, the Select_String returns nothing. If I switch the -ge to an -le, then it returns all the errors in all the files regardless of the date. Any ideas of what's going on?

    Thanks!

    Wednesday, February 22, 2017 2:53 PM
  • HI,

    you need to filter the files before you Select-String them:

    Get-ChildItem -Path $Path | Where-Object {$_.LastWriteTime -ge $date} | Select-String -Pattern "Error"

    After select-stringing them it's no longer a fileinfo, so it won't have a LastWriteTime anymore.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    Wednesday, February 22, 2017 3:11 PM