1

Spent a few days going through a few dozen examples but, unfortunately, not found a solution yet. Hoping you guys can help.

I need to search a bunch of log files at once and on each line check today's date and for a specific string - and importantly, i need a count of the two combined occurrences. I can do the individual search using Select-String. Even together. however, getting a count of it - while searching for both items on the same line has been the biggest hurdle. Some of logs are renamed overnight and a suffix appended to them - this should explain the search criteria I've used.

This is the code example:

**$dateStr = Get-Date -Format "yyyy-mm-dd"
$searchStr = 'some.class.name'
(Get-ChildItem -Filter "*info*.log*" -Recurse | Select-String -pattern "$dateStr.$searchStr" -AllMatches).matches.count**

This version (i have many), is perhaps the simplest version and more instructive to what i am trying to achieve and for those who are willing to help.

Nimster
  • 21
  • 1

1 Answers1

1

Assuming the date always precedes the part of the message you're searching for, use .* or .+ to describe whatever might be in between the two:

# Get the date string - no special metacharacters here, so safe to use as-is
$date = Get-Date -Format yyyy-mm-dd

# The keyword we're searching for might have metacharacters, like `.`, so remember to escape it
$word = [regex]::Escape('some.class.name')

# Now construct the pattern - use `.+` to describe "1 or more of any character" in between the date and the word we're searching for
$pattern = "${date}.+${word}"

# Pipe the results to Measure-Object, might speed up processing time
$count = (Get-ChildItem -Filter "*info*.log*" -Recurse | Select-String -Pattern $pattern -AllMatches |ForEach-Object Matches |Measure-Object).Count
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • That worked!! - thank you for your fully kitted out and descriptive response. I've learnt a bit more about Powershell from your answer. – Nimster Aug 26 '21 at 10:45