设置AD group ManagedBy 复选框

Powershell Set AD group ManagedBy_Powershell

$samaccountname = "123456"
$groupsid = "groupsid"
$UserDN = (Get-ADUser $samaccountname).distinguishedname
$GroupDN = (Get-ADGroup $groupsid).distinguishedname
$userAccount = "{0}\{1}" -f 'CONTOSO', $samaccountname
$rightGuid = Get-ItemProperty "AD:\CN=Self-Membership,CN=Extended-Rights,CN=Configuration,DC=contoso,DC=com" -Name rightsGuid | Select-Object -ExpandProperty rightsGuid
$Guid = [GUID]$rightGuid
$user = New-Object System.Security.Principal.NTAccount($userAccount)
$sid = $user.translate([System.Security.Principal.SecurityIdentifier])
$acl = Get-Acl AD:\$GroupDN
$ctrl = [System.Security.AccessControl.AccessControlType]::Allow
$rights = [System.DirectoryServices.ActiveDirectoryRights]::WriteProperty -bor [System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight
$intype = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::None
$group = [adsi]"LDAP://$GroupDN"
$group.put("ManagedBy", $UserDN)
$group.setinfo()
$rule = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($sid, $rights, $ctrl, $guid)
$acl.AddAccessRule($rule)
Set-Acl -acl $acl -path AD:\$GroupDN
$acl = Get-Acl AD:\$GroupDN
$access = $acl.Access | Where-Object { $_.IdentityReference -eq $userAccount }
if ($access -eq $null)
{
Write-Host "Cannot set Manager can not update membership list on Group $groupsid" -BackgroundColor DarkRed
}