I need your help to sort this scenario, where I need to get list of AD group and its members along with its MemberOf property in to CSV file. I’ve prepared a script by combining few article available over internet however I’ve stuck to pull “MemberOf” property value in to a CSV. Here is what I’ve prepared so far, please help me to get “MemberOF” property of a AD group.
Thanks Erik, thanks a lot for this. It will be nice if you also explain me this (%{($_ -split “,”)[0].Substring(3)}) -join “,” ).
I’m poor in that part. However I was trying this ($Record.“Member Of” = $Group.MemberOf -split (“,”) | Select-String -AllMatches “CN=”) which give me result but with (CN=). but with your trick it works as I was looking for. You make my day friend.
No problem, well % is just an alias for Foreach-Object, $_ is the incoming object and the split operator creates an array. [0] picks the first entry in that array (counting starts at 0, 1 would give you the second entry).
With the substring method you pick the start position on the string, since counting start at 0, using 3 gets you the 4th letter as a starting position (after CN=), you could use this with your code to remove the CN=. If you find more then one group, the code will create an array with an entry for each group, the join operator converts the array to a string with separators of your choice (in this case “,”). You could write the code like this:
Simply because me trying to solve it, caused me to have a difficulty myself.
Getting the data is easy, but getting it into that CSV is what messes me up.
Anyway, the best i’ve come up with is the following code.
It’s not perfect and you can read the process over on reddit.
$groups = Get-ADGroup -ldapfilter "(name=g*)" -Properties * |
where { $_.MemberOf -NE "" } | Select Name -first 10
# Create the columns for the CSV File
$H1='Group'
$H2='Members'
$H3='MemberOf'
# Add the columns into a variable that will be used to add data
$row = "" | Select-Object $H1,$H2,$H3
foreach($group in $groups){
$MemberOf = Get-ADPrincipalGroupMembership -Identity $group.name | Select Name -ExpandProperty Name
$Members = Get-ADGroupMember -Identity $group.name | select Name -ExpandProperty Name
IF($MemberOf.count -gt $members.Count){
for($i=0;$i -lt $MemberOf.Count; $i++)
{
$Output=@()
$row.$H1 = $Group.Name
$row.$H2 = $members[$i]
$row.$H3 = $MemberOf[$i]
$Output = $Output + $row
$Output
}
}else{
for($i=0;$i -lt $Members.Count; $i++)
{
$Output=@()
$row.$H1 = $Group.Name
$row.$H2 = $members[$i]
if($memberof.count -gt 1){ # I dont know why i need this, i just need it, otherwise if there is only 1 group
$row.$H3 = $MemberOf[$i] # it splits the groupname up in characters. Disatvantage is that it shows the group
}else{$row.$H3 = $MemberOf} # for each member.
$Output = $Output + $row
$Output
}
}
}
I reference a very good github page where you learn the important stuff with just a few pages.
After that it’s just practice. In that blogpost you see how i got into it.