Thursday, December 18, 2014

Get local admins remotely using PowerShell

Small script that I've created to retrieve local admins users remotely from a list of computers.

######################

$List = "127.0.0.1", "localhost"

### This can be change to $List = Get-Content C:\ComputerList.txt
### In order to include a large list of computers to go through them

######################

$Results = foreach ($l in $list)
{
    
    $Result = "" | Select-Object -Property ComputerName, LocalAdmin
    $Result.ComputerName = $l
    $AllUsers = Get-WmiObject -Class win32_groupuser -ComputerName $l -ErrorAction 'SilentlyContinue'
    $Local_Administrators = $AllUsers | Where { $_.GroupComponent -match 'administrators' }
    $Result.LocalAdmin = ""
    $Result.LocalAdmin = $Local_Administrators | ForEach-Object {`
        $PartComponent = $_.PartComponent;
        $output = $PartComponent.LastIndexOf('=');
        $output = $PartComponent.Substring($output);
        $output = $output.Substring(2);
        $output.TrimEnd('"')
    }
    $LocaAdminsCount = $Result.LocalAdmin.Count
    $ConvertToCSV = ""
    for ($i = 0; $i -le $LocaAdminsCount; $i++)
    {
        if ($i -lt ($LocaAdminsCount - 1))
        {
            $ConvertToCSV += $Result.LocalAdmin[$i] + ", "
        }
        else
        {
            $ConvertToCSV += $Result.LocalAdmin[$i]
        } # END IF
    } # END for loop
    $Result.LocalAdmin = $ConvertToCSV
    $Result
    
} # END foreach loop

$Results # Just display the result to the screen
$Results | Export-Csv $env:TEMP\LocalAdmin.csv

### Change the output location to whatever you would like

######################

Enjoy :-)

No comments:

Post a Comment