Powershell – List Users in Local Administrators Group

The following script lists all users in the local administrators group for all windows servers in the domainCouple of things:

  1. Get-ADComputer cmdlet can change to filter whatever you want. In my case I had 600 servers I wanted to check, but you could do windows 7 workstations just the same
  2. The Computer you are scanning needs to be turned on!
  3. No need to test-connection to check if the computer is on as the ADSI call errors quickly
  4. As it is an ADSI call it just errors automatically , as it is not a cmdlet (so no -erroraction stop parameter required for the try /catch function)
  5. I am using a try/catch so that even if the computer is not turned on, you still get output to the CSV

 

#Get all Computers where the operating system is reported as starting with windows server
#eliminates windows 7,8,10 etc
$Servers = Get-ADComputer -Filter ' OperatingSystem -like "Windows Server*" ' -properties OperatingSystem
$i = 1
$CSV = foreach ($Server in $Servers)
        {
        Write-Progress -Activity " $i of $($Servers.count)" #Write  aprogress bar so we know how fast we are gooing and how many we have
        try #Try to connect to the server and get details no need for -erroraction stop for some reason???
        {
            $LocalAdmin = ([ADSI]"WinNT://$($server.name)/Administrators").psbase.invoke('Members')  | %{$_.gettype().invokemember('Name', 'getproperty',$null,$_,$null)} 
            for ($n = 1; $n -lt $LocalAdmin.count; $n++) 
            {
            [PSCustomObject] @{Server = $Server.Name;OperatingSystem = $Server.OperatingSystem; LocalAdmin = $LocalAdmin[$n]}    
            }
            
        }
        catch #could not connect to server, so put a record in saying that 
        {
        [PSCustomObject] @{Server = $Server.Name; OperatingSystem = $Server.OperatingSystem;LocalAdmin = 'Error accessing server'} 
        }
       

       $i++
        }

$csv | export-csv -NoTypeInformation -path .\localadmin.csv 

 

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.