Automatically add AD user to Security group from a OU using powershell
Script will help you to add users from a specified OU to AD Security group.
#Variables
$TargetGroup = “Testing“
$TargetOU = “OU=Test,OU=UAT,OU=Corporate Group Users,OU=Corporate Group,DC=BBNTech,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
}
}
Comments