I am new to powershell, but I've been reading manuals and practiced a little bit. My objective is to List all users in all Security Groups under specified path. I have found the way to do it:
get-adgroup -Filter * -SearchBase "OU=Groups,DC=corp,DC=ourcompany,DC=Com" | %{Get-ADGroupMember $_.name} | ft name
But the problem is I do not see the group name. All I get is a bunch of users. It would be nice if someone could tell me how to display the group name before all the members of this group get listed. Thanks.
Gimme the codes!
powers, activate!The point being, just take your time and break it out into steps. I know that it's fun to try to get everything and the kitchen sink to fit into a one-liner with Powershell, but it's by no means required.
A few notes:
You don't need to do
Get-ADGroupMember
if you collect the Members property in the initialGet-ADGroup
Cmdlet. The good thing about this is that it halves the amount of calls you have to make to AD, which should make your script run faster, and it eases the burden on the domain controller.$G.Members will display all members of the group $G... in Powershell 3. In Powershell 2, you might still need to put another Foreach inside the Foreach there to enumerate through the group members. (Yo dawg, I heard you like loops...)
I use
Write-Host
here, which is gross. You should never really useWrite-Host
. Instead, you should be building and outputting objects, not text, but that was a whole other topic and I was too lazy to do that for this answer.Here is a much better solution. This will put everything in a 3 column csv with group name, username, and sam account name. A lot easier to figure out what group someone is in when there's 400 users in a group as you don't have to scroll.
I had to add
.name
after$group
to make this work for me.If you ever run into the
Size Limit
issue with groups containing more than 5000 members, you can change the one line as follows:Here is a scripts that exports all groups in a OU to a seperate file for each group with the group name and description. If someone wants that..