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

Time:02-24

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

CodePudding user response:

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
  • Related