Forum Discussion

TJCooper440's avatar
TJCooper440
Copper Contributor
Oct 03, 2023
Solved

Need help removing a security group from ACLS

What is the PowerShell to query all objects in an OU (security group OR user objects) then remove a group from the ACLS?   Query all groups in OU. Loop through results of Query (groups in this cas...
  • LeonPavesic's avatar
    Oct 04, 2023

    Hi TJCooper440,

     

    Here is a more robust PowerShell script that you can use to remove a security group from the ACLs of all objects in an OU:

     

     

    # Get the security group object
    $securityGroup = Get-ADGroup -Filter Name -EQ "MySecurityGroup"
    
    # Get all objects in the OU
    $ou = Get-ADOrganizationalUnit -Filter * -SearchBase "OU=MyOU,DC=example,DC=com"
    $objects = Get-ADObject -Filter * -SearchBase $ou.DistinguishedName
    
    # Filter the objects to only include security groups and user objects
    $objects = $objects | Where-Object { $_.ObjectClass -eq "Group" -or $_.ObjectClass -eq "User" }
    
    # Loop through the objects and remove the security group from the ACLs
    foreach ($object in $objects) {
    
        # Get the ACLs for the object
        $acls = Get-Acl -Path $object.DistinguishedName
    
        # Check if the security group is in the ACLs
        if ($acls.Access | Where-Object { $_.IdentityReference -eq $securityGroup.Sid }) {
    
            # Remove the security group from the ACLs
            $acls.RemoveAccessRule($securityGroup.Sid)
        }
    
        # Set the ACLs back to the object
        Set-Acl -Path $object.DistinguishedName -AclObject $acls
    }

     

    This script is more robust than the previous one because it:

    • Filters the objects to only include security groups and user objects. This is important because you may not want to remove the security group from the ACLs of other types of objects, such as computers or printers.
    • Checks to see if the security group is in the ACLs before removing it. This prevents you from accidentally removing the security group from the ACLs of an object if it is not already there.


    To use the script, replace MyOU with the name of the OU that you want to search, and replace MySecurityGroup with the name of the security group that you want to remove.

    Please click Mark as Best Response & Like if my post helped you to solve your issue.
    This will help others to find the correct solution easily. It also closes the item.


    If the post was useful in other ways, please consider giving it Like.


    Kindest regards,


    Leon Pavesic
    (LinkedIn)

Resources