Generally, windows administrators work on many Active Directory (AD) task, like adding new users to a group or multiple AD groups or removing the user from AD groups as part of their support work one can automate the adding user accounts to AD group then it eases the process, here are the simple steps this article explains how to add a single or multiple user accounts to AD group.
Powershell script to add user account to AD group
#Declaring advaced functions and parameters
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[string[]]$ADUsers,
[parameter(Mandatory=$true)]
[string]$ADGroupName
)
#we need to import Active Directory module
Import-Module ActiveDirectory
try {
$ObjectName = Get-ADGroup -identity $ADGroupName -EA stop
} catch {
Write-Warning "$ADGroupName : Unable to Find the AD group, Please check and try again"
return
}
foreach($userid in $ADUsers)
{
try {
$userobj = Get-ADUser -identity $userid.trim() -EA 0
if(!$userobj)
{
Write-Warning "$userid : Unable to Find the User ID, Please check and try again"
continue
}
Add-ADGroupMember -identity $ObjectName -Members $userobj -EA 0
Write-host "$userid : User has been added to $ADGroupName" -ForegroundColor Green
}
catch
{
Write-Warning "$userid : Something went wrong, user was not added"
}
}
Here are the simple steps to use this script, one can save this script as Add-ADUser.PS1
Syntax 1 : Add-ADuser.PS1 -ADusers Raja -ADGroupName "VMwarePower"
Syntax 2 : Adding Multiple Add user accounts to a single group
Add-ADuser.PS1 -ADusers Raja, Shekar, Tinku, Pawan, Aryan -ADGroupName "VMwarePower"
One can create a list of users in a text file add that too, for example you have 50 users in a text file as newusers.txt in the location C:\temp\newusers.txt folder, and you want add to a group, then here is simple way you can use the above script.
$newusers = get-content -path "C:\temp\Newusers.txt"
Syntax 1 : Add-ADuser.PS1 -ADusers $newusers -ADGroupName "VMwarePower"
Thank you for reading this article, if you have any questions please let us know.
Thank you for visiting my site, for any scripts in these articles you are testing please make sure you have tested this script in our lower environment before you run in production.
Leave a Reply Cancel reply