Loading...
 

PS Active Directory Code




Add or Remove a user from an AD Group

To Add a user:
$userdn = (Get-User -Identity "Domain\Username").DistinguishedName
$groupdn = (Get-Group -Identity "GroupName").DistinguishedName
$adgroup = [adsi]"LDAP://$groupdn"
$adgroup.member.add($userdn)
$adgroup.setinfo()

To Remove a user:
$userdn = (Get-User -Identity "Domain\Username").DistinguishedName
$groupdn = (Get-Group -Identity "GroupName").DistinguishedName
$adgroup = [adsi]"LDAP://$groupdn"
$adgroup.member.remove($userdn)
$adgroup.setinfo()


Get the SID of an Object

# First grab the raw objectsid attribute from an object
$objectsid = ([ADSI]"LDAP://CN=SomeObject,OU=SomeOU,DC=MyDomain,DC=Com").objectSid

# Create a new Security Identitifier object passing the byte
# array returned from your LDAP query to the constructor
$secid = New-Object System.Security.Principal.SecurityIdentifier($objectsid.Item(0), 0)

# Echo the string representation of the SID
Write-Host $secid.ToString()


Resolve a User's Primary Group

The primarygroupid attribute of an active directory user is a RID. Use the following procedure to resolve it to it's friendly name.
# Grab the DN of the user
$dn = (Get-Mailbox -Identity "DOMAIN\username").DistinguishedName

# Get the SID of the user so that we can get their primary group
$usersec = New-Object System.Security.Principal.NtAccount("domain", "username")
$usersid = ($usersec.Translate([System.Security.Principal.SecurityIdentifier])).Value

# Parse the Domain RID out of the user's SID
$domainrid = $usersid.Substring(0,$usersid.LastIndexOf("-") + 1)

# Get the PrimaryGroupID of the user
$userpgid = ([ADSI]"LDAP://$dn").PrimaryGroupID

# Construct the primary group SID by appending the PrimaryGroupID to the Domain RID
$primarygroupsid = $domainrid + $userpgid

# Search AD to resolve the primary group name
$primarygroupdn = [ADSI]"LDAP://<sid=$primarygroupsid>"
$primarygroupname = $primarygroupdn.Name

Show php error messages