Tuesday, February 15, 2011

Powershell: Write out local Administrators group membership to CSV

This powershell script will query a CSV containing a single list of servers to determine the membership of the local Administrators group. This script could be used to assist in determining HPA (Highly Privileged Access) accounts in a company.

While SYDI-Server can perform this task, some servers do not allow remote WMI connections. This script uses the same remote management interface as Computer Management to connect to the server. For this reason it could be used in conjunction with SYDI-Server to hit both WMI and non-WMI servers.

If your logged in account does not have access to the server being queried then you can try to net use \\server\IPC$ user:server\username * prior to running the command. The command should then use these impersonated credentials to connect.

This script only outputs the direct members of the local Administrators group. A second script is on this site which can be executed following this script to expand out the AD group memberships as well.

Here is the script.

cls
$csvfile = Import-Csv BadServer.csv
'"Server","Username","Type"' | Out-File -filepath "Users.csv"
foreach($line in $csvfile)
{
$strcomputer = $line.server
$computer = [ADSI]("WinNT://" + $strcomputer + ",computer")

#uncomment the following lines if you need to get all groups from the computer

# $computer.psbase.children | Where-Object{ $_.psbase.schemaClassName -eq 'group'} | foreach {
# '"' +$strcomputer + '","' + $_.name + '"' | Out-File -filepath "Groups.csv" -append
# #Write-Host $_.name
# }
$group = $computer.psbase.children.find("Administrators")
$members = $group.psbase.invoke("Members")
foreach( $member in $members)
{
#Write-Host $member.GetType().GetFields()
$compname = $member.GetType().InvokeMember("AdsPath", 'GetProperty', $null,$member, $null)
$strname = $compname.Remove(0,8).Replace("/","\")
'"' +$strcomputer + '","' + $strname+ '","' + $member.GetType().InvokeMember("Class", 'GetProperty', $null,$member, $null) + '"' | Out-File -filepath "Users.csv" -append
}

$members = $null
$group = $null
$computer = $null
}

Write-Host "done"
start .

No comments:

Post a Comment