Home > Mobile >  Powershell to export AD group members in each own name .CSV?
Powershell to export AD group members in each own name .CSV?

Time:06-22

I need to get the AD group membership in a separate GroupName.CSV file for each of these builtin AD groups in Domain.com/Microsoft Exchange Security Groups:

The Content of the GroupName.CSV will be the AD username / Displayname only and the Type eg. user or Group (since some of these AD groups are nested.

This is so I can copy-paste in case I need to recreate the AD group again in a quick manner.

$OU = 'OU=Microsoft Exchange Security Groups,DC=Domain,DC=com'
# Get adgroups from specific OU
$adGroups =  Get-ADGroup -Filter * -SearchBase $OU

# Iterate through adgroups and get ad group name and user name
$adGroupMembers = foreach ($Group in $adGroups) {
    Get-ADGroupMember -Identity $Group -Recursive | Select-Object @{Name='Group';Expression={$Group.Name}}, @{Name='Member';Expression={$_.Name}}
}
# export ad group name and user to csv file
$adGroupMembers | Export-Csv -Path D:\adGroupMembers.csv -NoTypeInformation

The above script just dump them all into one big .CSV file, it is hard to know which type of AD group member is.

CodePudding user response:

By changing your last line slightly and grouping them by groups, you can then easily export each members based on their group membership.

$adGroupMembers | Group-Object Group  | % { $_.Group | Export-Csv -Path "D:\$($_.Name)_adGroupMembers.csv" -NoTypeInformation }

CodePudding user response:

Maybe you can just add object class to your script ?

$OU = 'OU=Microsoft Exchange Security Groups,DC=Domain,DC=com'
# Get adgroups from specific OU
$adGroups =  Get-ADGroup -Filter * -SearchBase $OU

# Iterate through adgroups and get ad group name and user name
$adGroupMembers = foreach ($Group in $adGroups) {
    Get-ADGroupMember -Identity $Group -Recursive | Select-Object @{Name='Group';e={$Group.Name}}, @{Name='Member';e={$_.Name}},@{Name='objectClass';e={$_.objectClass}}
}
# export ad group name and user to csv file
$adGroupMembers | Export-Csv -Path D:\adGroupMembers.csv -NoTypeInformation

  • Related