Pages

3/27/2011

Powershell: Report Server Group Membership

Create an HTML report of each server in AD and its group memberships.

###########################################################################
#
#    server-group.ps1
#
#    Report group membership for each Windows Server in AD
#
###########################################################################

# Create $list of AD machine accounts for Windows Servers 
$strCategory = "computer" 
$strOS = "Windows*Server*"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry 
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher 
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("OperatingSystem=$strOS")
$colProplist = "dnshostname"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults) { 
    $objComputer = $objResult.Properties;  
    $Server = $objComputer.dnshostname
    $Server = $Server -replace "\s{2,}", ""
    $Server = $Server -replace "\.usa\.DOMAIN\.com", ""
    if ($Server) { $list = $list + $Server } #skip a null value
    }#foreach
 
# Prepare output file
"<HTML>" | out-file server-groups.html
"<HEAD>" | out-file server-groups.html -append
"<TITLE></TITLE>" | out-file server-groups.html -append
"</HEAD>" | out-file server-groups.html -append
'<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">' | out-file server-groups.html -append
"<H1>Servers' Group Membership</H1>" | out-file server-groups.html -append
 
foreach ($target in $list) {
    $ds = new-object directoryServices.directorySearcher 
    $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$target))" 
    $dn = $ds.findOne() 
    if ($dn) { #found
        $user = [ADSI]$dn.path 
        $userDE = [ADSI]"LDAP://$($user.distinguishedname)" 
        $user.name
        "<b>" + $user.name + "</b><BR>" | out-file server-groups.html -append
        $groups = $user.memberof
        foreach($group in $groups) {
            $strGroup = $group.split(',')[0]
            $strGroup = $strGroup.split('=')[1] 
            "     "+$strGroup
            "        " + $strGroup + "<BR>" | out-file server-groups.html -append
            }#foreach
        }#if
    }#foreach
"</BODY></HTML>" | out-file server-groups.html -append

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

No comments: