'powershell script to export all groups and members and the groups with in the group members
I'm new to scripting but I'm trying to get an export.xlsx of the all of the AD groups and their members and the groups within the group.
AD group name> group Members>... and if there are AD group(s) with in the group> export the members of that AD group
So far i have the following.
$groups = Get-adgroup -filter * -searchbase 'OU...DC=com'
foreach($group in $groups){
Get-adgroupmember $group |
select samaccountname |
export-csv C:\Temp\$group.csv -notype
}
Any help is greatly appreciated.
Solution 1:[1]
You can try something like this:
$groups = Get-ADGroup -Filter *
foreach($group in $groups){
$FileName = $group.Name
Get-Adgroupmember -Identity $group |
Export-CSV C:\Temp\$FileName.csv -notype
}
Solution 2:[2]
This is a good time for a recursive function.
Function Get-GroupMember
{
Param
(
$Group
)
$allmembers = foreach($member in Get-ADGroupMember $Group)
{
if($member.objectClass -eq 'Group')
{
Get-GroupMember -Group $member
}
else
{
[PSCustomObject]@{
Group = $Group.name
Member = $member.SamAccountName
Type = $member.objectClass
}
}
}
$allmembers | Export-Csv "C:\Temp\$($Group.name).csv" -notype
}
Call it like this
$groups = Get-adgroup -filter * -searchbase 'OU...DC=com'
Get-GroupMember -Group $groups
You didn't clearly specify what all info you wanted to export. The default object would have distinguishedname, name, objectClass, objectGUID, SamAccountName, and SID. If you want all those you could change the else portion to simply "$member". Otherwise, you can adjust what the custom object returns. This will create 1 file per group named groupname.csv. You could parameterize the export path as a next step.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mike Kennedy |
| Solution 2 | Doug Maurer |
