Jimmy
Jimmy

Reputation: 1

Filtering group memberships to copy from one user to another

I currently have working code that copies all group memberships of one user to another, taken from here: Copy group membership from one user to another in AD

Get-ADuser $user_to_copy -Properties MemberOf | Select-Object -ExpandProperty MemberOf | Add-ADGroupMember -Members $user_name

I would like to add a filter which prevents groups that start with a number from being added.

For example:

123_Group - Would not be added to the new user.

Group_123 - Would be added to the new user.

I've been playing around with Where-Object but can't get it to work how I would like.

| Where-Object {$_.MemberOf -Match '[a-z]*'}

The groups have "CN=... etc." at the start which I've tried to account for as well but to no avail (no output errors, just not the output I need/expect). I'm not sure if I'm just making a mistake or should be attempting this another way.

Any help/advice is greatly appreciated.

Thank you.

Upvotes: 0

Views: 458

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40918

Use .NET's Char.IsDigit method to check if the first character of the name is a numerical digit:

Get-ADuser $user_to_copy -Properties MemberOf `
  | Select-Object -ExpandProperty MemberOf `
  | Where-Object { -not [System.Char]::IsDigit($_[3]) } `
  | Add-ADGroupMember -Members $user_name

I use $_[3] (the fourth character) since the memberOf attribute is a list of distinguishedName, which will all start with CN= followed by the name of the group.

Update: If you want to filter out groups that start with a certain string, use something like this:

$badstring = "Computer"
Get-ADuser $user_to_copy -Properties MemberOf `
  | Select-Object -ExpandProperty MemberOf `
  | Where-Object { -not $_.Substring(3).StartsWith($badstring) } `
  | Add-ADGroupMember -Members $user_name

Upvotes: 2

Related Questions