PowerShell

Active Directory: Find users based on Attributes and add them to a Group with PowerShell

Active Directory objects are usually stored in organizational units. Sometimes these organizational units don’t refer to the site where the users work. The goal for this article is to retrieve these users and add them to a group. This blog post is designed to be a template of how to search users with a specific attribute and do something with the search results.

Let’s say we want to create some groups. Those groups should include all users from a specific site. Unfortunately, the users are spread over tons of organizational units, but we are lucky, the site attribute will give us the information we need.

The following code example shows a code which

  • gets all enabled users with a specific street address
  • add them to a group

Retrieve all users and add them to a Group

First, I create an universal security group “Bruno-Kreisky-Platz”.


New-ADGroup -Name 'Bruno-Kreisky-Platz' -GroupScope Universal -GroupCategory Security

1.PNG

Now I am looking for Active Directory users that have a street address attribute “Bruno-Kreisky-Platz” and “pipe” them to Add-ADPrincipalGroupMembership Here is the code in PowerShell ISE.


Get-ADUser -Filter 'streetaddress -like "*Bruno-Kreisky-Platz*"' -Properties streetaddress | Add-ADPrincipalGroupMembership -MemberOf 'Bruno-Kreisky-Platz'

1.PNG

Finally, we check our work.

1.PNG

Get-ADGroupMember 'Bruno-Kreisky-Platz' | Select-Object -Property Name

Finding attributes

Take a sample user and examine the attributes of the Active Directory user class to replace the streetaddress attribute from the previous example according to your needs.


Get-ADUser patrick -Properties *

1.PNG

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.