Extracting Group Name & Its Members in AD then Export to Excel.

Iron Contributor

Sharing Mode.

 

# Filter Groups in AD based on OU Test on localdomain.com
$searchBase = "OU=Test,DC=localdomain,DC=com"
$resultGroups = Get-ADGroup -Filter * -SearchBase $searchBase -Property * | Sort-Object Name 

# Create Excel File
$xlfile = "$($env:USERPROFILE)\Desktop\ADGroup_$(get-date -f "MM.dd.yyyy hh.mm tt").xlsx"
$excel = New-Object -ComObject excel.application
$excel.visible = $False
$wb = $excel.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)

$row = 1
$col = 1

ForEach($resultGroup in $resultGroups){

    $ws.Cells.Item($row,$col) = $resultGroup.Name
    $ws.Columns.AutoFit()

    # Get List of Members base on Group Name
    Get-ADGroupMember -Identity $resultGroup.DistinguishedName -Recursive | Select-Object -Property @{n="Members"; e={ $_.Name }} | Sort-Object Members | ForEach-Object {

        $row++
        $ws.Cells.Item($row,$col) = $_.Members
        
    }
    $col++
    $row = 1
}

# Close Excel File
$excel.DisplayAlerts = 'False'
$wb.SaveAs($xlfile)
$wb.Close
$excel.DisplayAlerts = 'False'
$excel.Quit()
Write-Host "Finished..." 

 

0 Replies