Search code examples
powershellforeachget-winevent

PowerShell: Get-Winevent doesn't work with multiple objects in foreach loop


I enabled the audit event group policy and then I added my test account to Groupname11.

When I try to run this without the other group names commented out I don't get anything from $Events.

I don't understand what I am doing wrong?

$Groups = @(
    #"Groupname8"
    #"Groupname9"
    #"AGroupname10"
    "Groupname11"
    #"Groupname12"
    )
    
    Foreach ($Group in $Groups){
    $Events = Get-WinEvent -FilterHashtable @{logname = 'Security'; ID = 4728; } | Where-Object {$_.Properties.Value -like "*$($Groups)*"}
    }
    $Events

Solution

  • You're currently overwriting $Events on each iteration of the loop.

    Move the assignment out of the loop so you capture the events for all the groups in $Events:

    $Groups = @(
        "Groupname8"
        "Groupname9"
        "AGroupname10"
        "Groupname11"
        "Groupname12"
    )
    
    $Events = Foreach ($Group in $Groups) {
        Get-WinEvent -FilterHashtable @{logname = 'Security'; ID = 4728; } | Where-Object { $_.Properties.Value -like "*$($Groups)*" }
    }
    
    $Events