Created
June 28, 2019 11:05
-
-
Save styk-tv/0a783de332fb1e2e9b70eb52cc362cf2 to your computer and use it in GitHub Desktop.
Export AD Groups with Members as CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#// Start of script | |
#// Get year and month for csv export file | |
$DateTime = Get-Date -f "yyyy-MM" | |
#// Set CSV file name | |
$CSVFile = "C:\AD_Groups"+$DateTime+".csv" | |
#// Create emy array for CSV data | |
$CSVOutput = @() | |
#// Get all AD groups in the domain | |
$ADGroups = Get-ADGroup -Filter "name -like 'AWS-Role*'" | |
#// Set progress bar variables | |
$i=0 | |
$tot = $ADGroups.count | |
foreach ($ADGroup in $ADGroups) { | |
#// Set up progress bar | |
$i++ | |
$status = "{0:N0}" -f ($i / $tot * 100) | |
Write-Progress -Activity "Exporting AD Groups" -status "Processing Group $i of $tot : $status% Completed" -PercentComplete ($i / $tot * 100) | |
#// Ensure Members variable is empty | |
$Members = "" | |
#// Get group members which are also groups and add to string | |
$MembersArr = Get-ADGroup -filter {Name -eq $ADGroup.Name} | Get-ADGroupMember | select Name, objectClass, distinguishedName, SamAccountName | |
if ($MembersArr) { | |
foreach ($Member in $MembersArr) { | |
if ($Member.objectClass -eq "user") { | |
$MemDN = $Member.distinguishedName | |
$UserObj = Get-ADUser -filter {DistinguishedName -eq $MemDN} | |
if ($UserObj.Enabled -eq $False) { | |
continue | |
} | |
} | |
Write-Host ($Member | Format-List | Out-String) | |
$Members = $Members + "##" + $Member.name + "~~" + $Member.SamAccountName + "~~" + $Member.distinguishedName | |
} | |
#// Check for members to avoid error for empty groups | |
if ($Members) { | |
$Members = $Members.Substring(2,($Members.Length) -2) | |
} | |
} | |
#// Set up hash table and add values | |
$HashTab = $NULL | |
$HashTab = [ordered]@{ | |
"Name" = $ADGroup.Name | |
"Category" = $ADGroup.GroupCategory | |
"Scope" = $ADGroup.GroupScope | |
"Members" = $Members | |
} | |
#// Add hash table to CSV data array | |
$CSVOutput += New-Object PSObject -Property $HashTab | |
} | |
#// Export to CSV files | |
$CSVOutput | Sort-Object Name | Export-Csv $CSVFile -NoTypeInformation | |
#// End of script |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment