我有一份用户、计算机和组的列表,其中随机的人是 AD 中的所有者。出于安全原因,我想清理它们,并将域管理员设为所有这些对象的所有者。有人可以帮忙编写一个 powershell 脚本吗?
我在谷歌上搜索,但没有任何收获。我找到了这个旧代码,但它似乎不起作用,一直收到所有者的错误。以域管理员身份运行,win10 机器。
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;
}
例如跑步
.\set-adowner.ps1 -Identity "RANDOMUSER" -Owner "domain admins"
一旦我运行了基本脚本,还想让它通过包含所有对象的 samaccountnames 的 txt 文件运行。
谢谢你的帮助,弗雷德
答案1
一位同事回答了我的问题,供其他感兴趣的人参考:
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;
}