Dynamically checking if a member exists in an Active Directory Security Group, Powershell

There may be a time you are provided a list of users and asked to ensure that the list of users belong to an Active Directory Security Group (AD SG).

You could manually check the list one-by-one against the Security Group's member tab, but what if your list is 50+ names long? That's really time consuming if you manually check the list one-by-one.

Let's save some time and check the list with a PowerShell script. This PowerShell script will check the list and let you know if the user already exists in the group, and if the user does not exist the PowerShell script will add the member to the Security group for you.

Script Instructions
Below are the step on how to accomplish this task.

Depending on how you received the list you should export the list to a text file, if applicable.

Open an elevated PowerShell console.

Type $groupName = "InsertGroupName", press Enter

Type $userList = Get-Content -Path , press Enter
Type ForEach($user in $userList) {, press Enter
Type Write-Host $user :: Already in the $groupName Security Group., press Enter
Type } Else {, press Enter
Type Add-ADGroupMember -Identity $groupName -Members $user, press Enter
Type }, press Enter


Explanation of Script

First, we are declaring a variable of $groupName and initializing the variable to a name of a valid Active Directory Security group name.

Second, we are declaring a variable of $userList and initializing the variable with the names provided within the list of names.

Finally, we are starting the heart of the script. Using a foreach loop we iterate through the provided user list. The script will output if the user is already a member of the security group and if the user is not apart of the security group the script will add the member using the Add-ADGroupMember cmdlet.

Entire Script

$groupName = "InsertGroupName"
$userList = Get-Content -Path "PathToTextFile"
ForEach($user in $Users) {
Write-Host $user :: Already in the $groupName Security Group.
} Else {
Add-ADGroupMember -Identity $groupName -Members $user
}


comments powered by Disqus