Managing Active Directory (AD) groups can often require bulk updates, such as adding multiple computers to a specific group. PowerShell provides a powerful way to automate these tasks, making the process efficient and straightforward.
Active Directory Module is required, if you already have installed RSAT tools (Remote Server Administration Tools) on your device, then the Active Directory module should be installed and imported by default.
Create a list of devices
Create a text file with all the devices that you want to add to an AD Group, as shown below:
Add the devices to an AD Security Group
The first thing we need to do is to import the computers list, by using the Get-Content command.
#Import the computers list and assign to a variable
$devices = Get-Content "C:\temp\computers.txt"
Then we need to assign the Security Group name to a variable
#Define the AD Security Group name
$groupName = "ReplaceWithYourADGroupName"
finally, we’re going to loop through each device in the $devices list and add to the AD Security Group
#Loop through each computer and add it to the group
foreach ($device in $devices) {
try {
Add-ADGroupMember -Identity $groupName -Members $device
Write-Host "Successfully added $device to $groupName"
} catch {
Write-Host "Failed to add $computer"
}
}
here’s the full script:
#Import the computers list and assign to a variable
$devices = Get-Content "C:\temp\computers.txt"
#Define the AD Security Group name
$groupName = "ReplaceWithYourADGroupName"
# Loop through each computer and add it to the group
foreach ($device in $devices) {
try {
Add-ADGroupMember -Identity $groupName -Members $device
Write-Host "Successfully added $device to $groupName"
} catch {
Write-Host "Failed to add $device"
}
}
Verify the addition
After running the script, it’s always a good practice to check whether the devices got added to the group or not, you can check the members of the group using the following command:
Get-ADGroupMember -Identity $groupName
you can also export the current members of the group to a CSV file
Get-ADGroupMember -Identity $groupName | Export-Csv -Path "c:\temp\$groupName-members.csv
Conclusion
Using PowerShell to add computers to an Active Directory group simplifies management tasks and enhances efficiency. By automating the process, you can save time and reduce the likelihood of errors. Always ensure you have the necessary permissions and validate your changes to maintain the integrity of your Active Directory environment.