Automatically add users to a security group with PowerShell

Hi All,

Sometimes you may find yourself needing to add a large number of users to a particular AD Security group. Using a PowerShell script, you can automate this process and target users based on the value of any AD user attribute.

In the below example, the script targets all users in a particular OU – any users in the OU that are not a member of the chosen group are added automatically.

Before running the script, set the variables (in bold) at the beginning of the script with the name of your AD group and the distinguished path of the OU containing the user accounts. If you would like to target users in a different way, you can edit the user query on line 5.

If you would like to routinely run this script, you may opt to add it as a scheduled task.

#Variables
$TargetGroup = “AD Security Group
$TargetOU = “OU=Users Accounts,DC=risualblogs,DC=com
#Target user query
$UserAccounts = Get-ADUser -Filter * | ?{$_.DistinguishedName -like “*$TargetOU*” -and $_.Enabled -eq “True”}
ForEach($User in $UserAccounts)
{
$UsersName = $User.Name
#Check for group membership
$Membership = Get-ADGroup $TargetGroup | Get-ADGroupMember | ?{$_.Name -eq $UsersName}
if(!$Membership)
{
“Adding $UsersName to $TargetGroup”
Get-ADGroup $TargetGroup | Add-ADGroupMember -Members $User -Verbose
}
}

Hope this helps

 

Post to Twitter

Leave a Comment

Your email address will not be published. Required fields are marked *