PShell Cmdlet for Group Names

Hi Community,

I tried to run this command and it comes up with blank memberof column. I want trim all DN stuff in memberof column.
Can you anyone suggest what is wrong this command producing blank MemberOf colum . PowerShell version 3.0

Get-ADUser -Filter “Name -like ‘'" -SearchBase “OU=Viamonstra,DC=adventureworks,DC=local” -SearchScope OneLevel -Properties * | Select-Object Name `
,@{Label=“Memberof”;expression={(Get-ADUser -Filter "Name -like '
’” -SearchBase “OU=Viamonstra,DC=adventureworks,DC=local” -SearchScope OneLevel -Properties * | `
ForEach-Object ($_.memberof | Get-ADGroup | Select-Object Name))}}

That is a lot of code just to get a group name, when you could potentially just use…

(Get-ADUser -Filter * -Properties ) `
| % {"
12 + ’ ’ + $_.SamAccountName + ’ ’ + "”*12; Get-ADPrincipalGroupMembership $_.SamAccountName | select Name}

See the help file for more details on Get-ADPrincipalGroupMembership

Hey Aleem,
There are several issues her

  1. You are using -Properties *, but you really only want Name and MemberOf. This is putting unnecessary stress on your DC to generate results with all of the Attributes when you really only want 2. -Properties Name, MemberOf would be better.
  2. Get-ADUser -Filter “Name -like ‘'" is getting all User accounts in your specified OU. You are then pipeing that into Select-Object and then doing Get-ADUser -Filter "Name -like '’” again. So for every account in your OU you are getting every account in your OU a second time. This is very inefficent and very unnecessary since you already have the MemberOf property in your Object from when you ran Get-ADUser the first time.
  3. I see what you are trying to do with pipeing the MemberOf properties to Get-ADGroup and then using the Name property of resulting Group Object, and that is one way to do it. The only word of causion here is that this puts and additional query to your domain controller for every group in every user, and if the same group is added to multiple users, then you domain controller is queried multiple times for that group.

Here is a sample of how to do what you were attempting

Get-ADUser -Filter "*" -SearchBase "OU=Viamonstra,DC=adventureworks,DC=local" -SearchScope OneLevel -Properties Name, MemberOf |
Select-Object Name, @{Label="Memberof";expression={($_.memberof | Get-ADGroup | Select-Object -ExpandProperty Name) -Join ","}}

Another option is to used something like RegEx to trim off all the unwanted part of the DN from your MemberOf values. This way you don’t have to query the Domain Controller for the group name. You just pull it out of the DN.

Get-ADUser -Filter "*" -SearchBase "OU=Viamonstra,DC=adventureworks,DC=local" -SearchScope OneLevel -Properties Name, MemberOf |
Select-Object Name, @{Label="Memberof";expression={(($_.memberof | Select-String -Pattern "^CN=(.*?),").matches | ForEach-Object {$_.Groups[1].value}) -join ","}}

Thanks Heaps!

Curtis Smith