Pages

3/27/2011

Powershell: Export Group Membership

Putting the pieces together
This post pulls together some of my previous fragments into something more specifically useful.

###########################################################################
#
#  server-group.ps1
#
#       Export group membership for each Windows Server in AD
#              if the group name contains WSUS
#
###########################################################################

#delete output file if it exists
if ( test-path wsus-server-groups.csv ) { remove-item wsus-server-groups.csv }

# 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
"Server, Group" | out-file -encoding ASCII  wsus-server-groups.csv # output headings
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
       $groups = $user.memberof
       foreach($group in $groups) {               {
           $strGroup = $group.split(',')[0]
           $strGroup = $strGroup.split('=')[1] 
           "     "+$strGroup
           if ($strGroup -match "WSUS") {
               $Target+", "+$strGroup | out-file -encoding ASCII  wsus-server-groups.csv -append
               }#if
           }#foreach
    }#if
}#foreach
###########################################################################

No comments: