Resolves the user and the group first, reports precisely which one was not found when something is wrong, and skips the change when the user is already a member. Both objects are addressed by distinguished name for the actual write, so an ambiguous name cannot send the membership to the wrong group.
powershell
# Add a User to an AD Group
# Single use case: add one user to one security/distribution group
#-----------------------------------------------------------------
function Write-Log {
param($Message)
Write-Host "<WRITE-LOG = `"*$Message*`">"
}
# --- Parameters (replace via ServerEngine API parameters if needed) ---
$SamAccountName = "j.doe"
$GroupName = "IT-Admins"
if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {
Write-Log "ActiveDirectory module not available on this host!"
return
}
Import-Module ActiveDirectory
$user = Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'" -ErrorAction SilentlyContinue
$group = Get-ADGroup -Filter "Name -eq '$GroupName'" -ErrorAction SilentlyContinue
if ($null -eq $user) { Write-Log "User not found: $SamAccountName"; return }
if ($null -eq $group) { Write-Log "Group not found: $GroupName"; return }
$isMember = Get-ADGroupMember -Identity $group.DistinguishedName -ErrorAction SilentlyContinue |
Where-Object { $_.SamAccountName -eq $user.SamAccountName }
if ($isMember) {
Write-Log "$SamAccountName is already a member of $GroupName."
return
}
Add-ADGroupMember -Identity $group.DistinguishedName -Members $user.DistinguishedName
Write-Log "$SamAccountName added to group $GroupName."Run it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
More in Active Directory
Active Directory User Onboarding with PowerShell
2026-08-17Active Directory User Offboarding with PowerShell
2026-08-17Disable an Active Directory User with PowerShell
2026-08-17Enable an Active Directory User with PowerShell
2026-08-17Unlock an Active Directory Account with PowerShell
2026-08-17Reset an Active Directory Password with PowerShell
2026-08-17Ready when you are.
Try ServerEngine free for 7 days.