Private/Add-UserToGroup_ADSI.ps1
function Add-UserToGroup_ADSI { <# .SYNOPSIS Adds a user to an AD group using distinguished names and ADSI. .PARAMETER UserDN The user’s distinguished name. .PARAMETER GroupDN The group’s distinguished name. .OUTPUTS Returns $true if added or already present, $false if failed. #> param( [Parameter(Mandatory)][string]$UserDN, [Parameter(Mandatory)][string]$GroupDN ) $timestamp = "[" + (Get-Date -Format "dd/MM/yy HH:mm:ss") + "]" try { $group = [ADSI]"LDAP://$GroupDN" if ($group.IsMember("LDAP://$UserDN")) { Write-Output "$timestamp : User is already a member of group." return $true } $group.Add("LDAP://$UserDN") $group.SetInfo() Write-Output "$timestamp : Successfully added user to group." return $true } catch { Write-Output "$timestamp : ERROR - Failed to add user to group: $($_.Exception.Message)" return $false } } |