Created
September 25, 2024 15:20
-
-
Save martinsohn/5f3945254b70f62291f8b177f1cb6181 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Remove one account from Owner and all non-inherited Allow ACEs on all computers throughout the domain | |
# 1. Replace "DomainJoin" with the unwanted account's name | |
# 2. Run script | |
$ErrorActionPreference = "Stop" | |
# Old owner | |
$OldOwnerSAM = Get-ADUser "DomainJoin" | select -ExpandProperty SamAccountName | |
# New owner | |
$newOwner = Get-ADGroup "Domain Admins" | |
$newOwnerSecurityIdentifier = New-Object System.Security.Principal.SecurityIdentifier($newOwner.SID) | |
# Get all AD objects | |
$ComputerDNs = Get-ADComputer -Filter * | select -ExpandProperty DistinguishedName | |
# Loop through each AD object | |
foreach ($objDn in $ComputerDNs) { | |
# # Get the ACL | |
$acl = Get-Acl "AD:$objDn" | |
$ACLChanged = $false | |
# If unwanted account is Owner, change to new Owner | |
if ($acl.Owner -like "*\$OldOwnerSAM") { | |
Write-Host ""; Write-Host $objDn | |
$acl.SetOwner($newOwner.SID) | |
$ACLChanged = $true | |
"Replacing owner." | |
} | |
# If unwanted account has Allow ACEs, remove the ACE | |
$oldOwnerACEs = $acl.Access | ? {$_.IsInherited -eq $false -and $_.IdentityReference -like "*\$OldOwnerSAM" -and $_.AccessControlType -eq "Allow"} | |
foreach ($ace in $oldOwnerACEs) { | |
if(!$ACLChanged) {Write-Host "";Write-Host $objDn} | |
$acl.RemoveAccessRule($ace) | Out-Null | |
$ACLChanged = $true | |
Write-Host "Removing ACE: $($ace.ActiveDirectoryRights) $($ace.ObjectType)" | |
} | |
# Update ACL if it was changed | |
if ($ACLChanged) { | |
$acl | Set-Acl | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment