regexpowershellselect-string

Powershell/Regex to count number of times a date range appears


I am working on a script to pull metrics from a log file. Here is an example from the log.

2/21/2022 3:29 PM: Requested username - Found disabled account with matching CATIID named username - Account username reactivated

3/21/2022 3:37 PM: username - No account found. Creating new account.

4/26/2022 1:25 PM: username- Disabled account found. Re-enabling 
account.

4/26/2022 1:25 PM: username - Active account found. Added to requested groups and updated charge code.

4/26/2022 1:25 PM: username - Disabled account found. Re-enabling account.

I need to be able to filter this to only count the number of times "Reactivated or Re-enabling" appears but also only for the month we are auditing.

Expected count from above would be 2 for the month of April.

I attempted to start filtering by using

$acc1 = Get-Content $accountcreatedpath | Select-String -pattern "$reactivationmonth/"
$acc2 = $acc1 | Select-String -pattern "/2022"
$acc3 = $acc2 | Select-String -NotMatch "$reactivationmonth/2022"
$accountscreated1 = ($acc3).Count

However this will miss any entries that occur when the month and day are the same. Any help greatly appreciated.


Solution

  • You can use

    $acc1 = '2/21/2022 3:29 PM: Requested username - Found disabled account with matching CATIID named username - Account username reactivated
    3/21/2022 3:37 PM: username - No account found. Creating new account.
    4/26/2022 1:25 PM: username- Disabled account found. Re-enabling
    account.
    4/26/2022 1:25 PM: username - Active account found. Added to requested groups and updated charge code.
    4/26/2022 1:25 PM: username - Disabled account found. Re-enabling account.'
    $reactivationmonth=4
    $rx = "(?m)^$reactivationmonth/\d{1,2}/20\d{2}.*?\b(Reactivated|Re-enabling)\b"
    ([regex]::Matches($acc1, $rx )).count
    

    Output is 2. See the regex demo.

    Details: