0

I have a list of users, computer, and groups that random people are the owner of in AD. I'd like to clean them up for security reasons and just make domain admins the owner for all these objects. Can someone assist with a powershell script for this?

I google searched without any luck. I found this old code but it doesn't seem to work, keep getting an error for the owner. Running as a domain admin, win10 machine.

Param (
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)][string]$Identity,
[parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true)][string]$Owner
)

try {
  $oADObject = Get-ADObject -Filter { (Name -eq $Identity) -or (DistinguishedName -eq $Identity) };
  $oAceObj   = Get-Acl -Path ("ActiveDirectory:://RootDSE/" + $oADObject.DistinguishedName);
} catch {
  Write-Error "Failed to find the source object.";
  return;
}

try {
  $oADOwner   = Get-ADObject -Filter { (Name -eq $Owner) -or (DistinguishedName -eq $Owner) };
  $oNewOwnAce = New-Object System.Security.Principal.NTAccount($oADOwner.Name);
} catch {
  Write-Error "Failed to find the new owner object.";
  return;
}

try {
  $oAceObj.SetOwner($oNewOwnAce);
  Set-Acl -Path ("ActiveDirectory:://RootDSE/" + $oADObject.DistinguishedName) -AclObject $oAceObj;
} catch {
  $errMsg = "Failed to set the new new ACE on " + $oADObject.Name;
  Write-Error $errMsg;
}

e.g. Running .\set-adowner.ps1 -Identity "RANDOMUSER" -Owner "domain admins"

Also would like to have it run through a txt file with all the objects' samaccountnames, once I get the base script running.

Thank you for any help, Fred

1 Answer 1

0

A coworker answered my question, for anyone else that is interested:

Param (
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)][string]$Owner
)

$Identities = Import-Csv .\identities.csv

foreach ($obj in $Identities) {

  $Identity = $obj.sAMAccountName;

  Write-Host "Setting ownership for $Identity..."
  #Get the object of the identity (group, user, computer account, etc.) you want to change
  $oADObject = Get-ADObject -Filter { (sAMAccountName -eq $Identity) -or (sAMAccountName -eq $Identity) } -properties sAMAccountName;
  $oAceObj   = Get-Acl -Path ("ActiveDirectory:://RootDSE/" + $oADObject.DistinguishedName);

  #Get the object of the account you want to take ownership of the object above
  $oADOwner   = Get-ADObject -Filter { (sAMAccountName -eq $Owner) -or (sAMAccountName -eq $Owner) } -properties sAMAccountName;
  $oNewOwnAce = New-Object System.Security.Principal.NTAccount($oADOwner.sAMAccountName);

  #Set owner of object
  $oAceObj.SetOwner($oNewOwnAce);
  Set-Acl -Path ("ActiveDirectory:://RootDSE/" + $oADObject.DistinguishedName) -AclObject $oAceObj;

}
1
  • 1
    -Filter { (sAMAccountName -eq $Identity) -or (sAMAccountName -eq $Identity) } you can never be too sure...
    – Massimo
    Apr 12, 2023 at 20:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .