0

As title says I need to get a specific part of a group name of group of users. Yup, Get-ADPrincipalGroupMembership allows to get user's groups. But it returns all user's groups (while I would like to get an exact one) and, as I understood, only for a exact user.

So I have three OUs. Each OU has users. Each user is member of a few groups, but I need to get a group(s) with a standard name per user. And standard name is department - X, where X part is specific for each user. So in a result I want to get a table, where will be Name, SamAccountName and X part of the group(s).

Hence, I need:

  1. Get list of users and it's groups from exact OU;
  2. From list of all users and it's groups I need to get group that has standard name per user. Standard name is department - X, where X part is specific for each user, and one user could has more than one group with the standard name;
  3. Per user I need to get X part from group(s) with the standard name.

1 Answers1

0

I would try something like that:

Get-ADUser -filter * -SearchBase "OU=OU1,OU=OU2,OU=OU3,DC=domain,DC=local" -Properties memberOf | % { [PSCustomObject]@{ Name = $_.Name; SamAccountName = $_.SamAccountName; Groups = ($_.MemberOf | ? { $_ -match "department" } | % { $_.Split(',')[0].Split('=')[1].Replace("department - ","") }) -join "," } }

This gets all the users from a given OU together with their membership. The value of a memberOf property is a DN of the group as a string, so somethinglike CN=group,OU=OU1,DC=domain,DC=local. Out of those it selects only entries that match department and splits the DN by comma and equal sign to get the CN part (which should match group's name).

raspy
  • 3,995
  • 1
  • 14
  • 18
  • Hi! Thanks a lot for your solution! It dramatically decreased amount of time, that I could spent on creating of something mine But even if I succeed to apply your solution for my case, I troubled with using of double replacement. Appeared, that needed "department - X" could vary a little, so I would like to apply a few Replace("department - ","") options. Is that possible to put such in your one-liner? – the_Alekhnovich Aug 02 '21 at 09:01
  • Sure, it's just a string manipulation so you should be able to chain additional operations, i.e. `.Replace("department - ","").Replace("something","something else")` etc. – raspy Aug 03 '21 at 10:20
  • Thanks! Seems like I just need to learn PS' syntax better ¯\_(ツ)_/¯ But I have one last question: when I export result of the string into .CSV spreadsheet, in column with department tags instead of a few department tags value "System.Object[]". So could I can export result into a spreadsheet, but keep a few department tags as value of a cell – the_Alekhnovich Aug 03 '21 at 14:29
  • Sure. In that case you may convert this array to a string by joining elements, i.e. `Group=(...) -join ","`. I'll update the answer. – raspy Aug 04 '21 at 12:36