Search EventLogs all DCs in Forest

I have been testing this bit of code:

Get-EventLog “Directory Service” | Where-Object {$_.EventID -eq 1864}

and works great on a local DC but was hoping to first get all DC’s in the forest then query for that EventID:

…this works on its own as well:

foreach ($domain in ((get-adforest).domains)) { get-addomaincontroller -filter * -server $domain  | sort hostname  | select -Property hostname }

How would I pipe the second into the first?

Usually there are several ways to accomplish a given task


$HostNames = foreach ($domain in ((get-adforest).domains)) { get-addomaincontroller -filter * -server $domain | sort hostname | select -Property hostname }
Foreach($Hostname in $Hostnames){
Get-EventLog “Directory Service” -ComputerName $Hostname | Where-Object {$_.EventID -eq 1864}
}

BTW: Get-WinEvent is the more modern and flexible option to get events from the event log

Under an admin ise, I’ve tried your code in two different forests and although the $Hostnames has the correct fqdn of the DCs, it appears the second foreach has an issue:


Get-EventLog : The network path was not found.
At line:3 char:5

  • Get-EventLog "Directory Service" -ComputerName $Hostname | Where- </pre> for each host object in the pipeline.
    

I’ve also tried this Get-WinEvent code in these two forests:

$HostNames = foreach ($domain in ((get-adforest).domains)) { get-addomaincontroller -filter * -server $domain  | sort hostname  | select -Property hostname }
Foreach($Hostname in $Hostnames){
    Get-WinEvent -LogName "Directory Service"  -ComputerName $Hostname  | Where-Object {$_.EventID -eq 1864}
}

but get a different error in each forest for each host object in the pipeline:

Get-WinEvent : The RPC server is unavailable

Sometimes it helps to see what’s going on … at least for me. :wink:

You could have checked what’s in ‘$HostNames’. That might have guided you already to the issue. OR you could have put a ‘Write-Debug’ or ‘Write-Verbose’ to the loop to show what’s used as the ‘$Hostname’

Anyway … the solution should be: Either you extract the ‘naked’ HostNames in your $HostNames like this:

$HostNames = foreach ($domain in ((get-adforest).domains)) { get-addomaincontroller -filter * -server $domain  | sort hostname  | select -ExpandProperty hostname }
!! PLease pay attention to the last 'Select-Object' !!

Or you use the ‘HostName’ property of your ‘$Hostname’ loop variable … like this:

Foreach($Hostname in $Hostnames){
    Get-WinEvent -LogName "Directory Service"  -ComputerName $($Hostname.HostName)  | Where-Object {$_.EventID -eq 1864}
}

Or like this:

Foreach($Hostname in $Hostnames.HostName){
    Get-WinEvent -LogName "Directory Service"  -ComputerName $Hostname  | Where-Object {$_.EventID -eq 1864}
}

thank you Olaf…going to play a bit