Remove a user/group permission on an AD Object via PowerShell

Scenario: You want to remove a users permission to an AD Object via PowerShell. This is the equivalent of opening Active Directory Users and Computers, finding your AD object (user, computer, ect), and removing the users permission from the Security Tab.

Scriptlets:  We are going to remove the user   domainjdoe from the AD Computer  test_computer.

 

#Set these variables
$DistinguishedName = "CN=test_computer,OU=Test,OU=Domain,DC=com"
$user = "domainjdoe"

#Collect the current ACL
$Acl = Get-Acl $DistinguishedName 

#Loop each access permission in the ACL
foreach ($access in $acl.Access) {
        if ($access.IdentityReference.Value -eq $user) {
        $acl.RemoveAccessRule($access)
        } 
}

#Set the ACL Back to the AD Object
set-acl $DistinguishedName  -AclObject $acl

 

Lets say you wanted to do this for every ADObject in a specific OU, run the following

#Set these Variables
$strOU = "CN=test,DC=Domain,DC=Com"
$Obj = get-adobject -searchbase $strOU -properties DistinguishedName,DisplayName -Filter * | Select DisplayName,DistinguishedName
$Obj = $obj | Sort DisplayName
$user = "domainjdoe"
$counter = 0

#Set AD as the location to find the user objects.
Set-Location ad:

#Loop it
$Obj | Select -first 5 | %{
#Increase counter
$Counter++
#Display Output
"
$counter / $($obj.count): Removing $User from $_.DisplayName - $_.DistinguishedName
-----------------------------------------------------------------------
"
#Get the current ACL for the AD Object
$DN = $_.DistinguishedName
$Acl = Get-Acl $DN 

#Loop each Access Level in the ACL And Remove for the User
foreach ($access in $acl.Access) {
       if ($access.IdentityReference.Value -eq $user) {$acl.RemoveAccessRule($access)} }

#Setting the Modified ACL back to the AD Object
set-acl $DN  -AclObject $acl

#reset variables
$ACL = $Null
$DN = $null
}

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: