The following script copies users from one Active directory group into another active directory group. If the user is already in the new group, then no action is taken.
# Import the Active Directory module if it's not already loaded
if (-not (Get-Module -Name ActiveDirectory)) {
Import-Module ActiveDirectory
}
# Specify the name of the source and target Active Directory groups
$sourceGroupName = "SourceGroupName"
$targetGroupName = "TargetGroupName"
# Get all members of the source Active Directory group
$sourceGroupMembers = Get-ADGroupMember -Identity $sourceGroupName | Where-Object {$_.objectClass -eq "user"}
# Get all members of the target Active Directory group
$targetGroupMembers = Get-ADGroupMember -Identity $targetGroupName | Where-Object {$_.objectClass -eq "user"}
# Iterate through the source group members and add them to the target group
foreach ($user in $sourceGroupMembers) {
# Check if the user is already a member of the target group
if ($targetGroupMembers -notcontains $user) {
# Add the user to the target group
Add-ADGroupMember -Identity $targetGroupName -Members $user.SamAccountName
Write-Host "Added $($user.SamAccountName) to $targetGroupName"
}
else {
Write-Host "$($user.SamAccountName) is already a member of $targetGroupName"
}
}
Moves users where the Distinguished Name matches a pattern
The following script copies members of an Active Directory Group into another Active Directory group where the name matches a particular pattern.
# Import the Active Directory module if it's not already loaded
if (-not (Get-Module -Name ActiveDirectory)) {
Import-Module ActiveDirectory
}
# Specify the name of the source and target Active Directory groups
$sourceGroupName = "SourceGroupName"
$targetGroupName = "TargetGroupName"
# Get all members of the source Active Directory group
$sourceGroupMembers = Get-ADGroupMember -Identity $sourceGroupName | Where-Object {$_.objectClass -eq "user" -and $_.SamAccountName -like "*SVC*"}
# Get all members of the target Active Directory group
$targetGroupMembers = Get-ADGroupMember -Identity $targetGroupName | Where-Object {$_.objectClass -eq "user"}
# Iterate through the source group members and add them to the target group
foreach ($user in $sourceGroupMembers) {
# Check if the user is already a member of the target group
if ($targetGroupMembers -notcontains $user) {
# Add the user to the target group
Add-ADGroupMember -Identity $targetGroupName -Members $user.SamAccountName
Write-Host "Added $($user.SamAccountName) to $targetGroupName"
}
else {
Write-Host "$($user.SamAccountName) is already a member of $targetGroupName"
}
}