Search code examples
powershellgrepexport-to-csv

Reporting keyword occurrence every minutes using Grep in Powershell


I need to report keyword occurrence using grep with power-shell and export the result in csv format if possible.

I need command similar to this one (it doesn't work for me in powershell)

cat .\PlaySound.txt | grep "Keyword" | grep $(date --date="@$(($(date +%s) - 3600))" "+%d/%b/%Y:%H") | wc -l

For exemple:

  • 17:20 SomeKeyword : 13
  • 17:21 SomeKeyword : 23
  • 17:22 SomeKeyword : 18
  • 17:23 SomeKeyword : 11
  • ...
  • 18:20 SomeKeyword : 10

Solution

  • I'm assuming the main issue is generating and formatting the timestamp?

    In PowerShell, the equivalent would be:

    Get-Date (Get-Date).AddHours(-1) -UFormat "+%d/%b/%Y:%H"
    

    So to recreate the whole pipeline we can do something like this:

    $timestamp = Get-Date (Get-Date).AddHours(-1) -UFormat "+%d/%b/%Y:%H"
    Get-Content .\PlaySound.txt |Where-Object {$_ -match 'Keyword' -and $_ -match $timestamp} |Measure-Object -Line |Select-Object -Expand Lines