Try the following:
# Define an array to store the results
$adminGroupMembers = @()
# Get a list of servers in your domain
$servers = Get-ADComputer -Filter {OperatingSystem -like "*Windows*Server*"} | Select-Object -ExpandProperty Name
# Iterate through each server
foreach ($server in $servers) {
# Try to establish a remote session to the server
try {
$session = New-PSSession -ComputerName $server -ErrorAction Stop
# Retrieve the members of the Local Administrators group
$members = Invoke-Command -Session $session -ScriptBlock {
$group = [ADSI]"WinNT://./Administrators,group"
$members = $group.Invoke("Members") | foreach { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) }
$members
}
# Add server and its administrators to the results array
$adminGroupMembers += [PSCustomObject]@{
Server = $server
Administrators = $members -join ', '
}
# Close the remote session
Remove-PSSession -Session $session
} catch {
Write-Host "Failed to connect to $server: $_"
}
}
# Export the results to a CSV file
$adminGroupMembers | Export-Csv -Path "LocalAdmins.csv" -NoTypeInformation
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin