首页 > 解决方案 > Remove all groups withen a specific OU

问题描述

I'm attempting to make an AD cleanup script that will go through a terminated OU and verify all users are removed from specific OU's. currently if I run it it will remove all users in the terminated OU from all OU's. I might just be blind but is there an easy way to have it only remove groups from selected OU's?

$OUs = "OU=Terminated,OU=####,OU=####,DC=####,DC=####"

$results = foreach ($OU in $OUs) {
    get-aduser -SearchBase $OU -filter * -properties MemberOf | foreach-object {
        ? $_.MemberOf -like "*OU I want removed*" | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false -whatif
    }
}
$results | Export-Csv '.\Users groups have been remoed from.csv' -NoTypeInformation

I thought it would work, however all it gives me is:

Where-Object : A positional parameter cannot be found that accepts argument 'Microsoft.ActiveDirectory.Management.ADPropertyValueCollection'.
At C:\###\###\###\accounts script.ps1:8 char:13
+             ? $_.MemberOf -like "*Distrobution Lists*" | <#%{$keep -n ...

标签: powershellactive-directorydata-cleaning

解决方案


鉴于您有一个单独的组 OU,您可以遍历已终止用户拥有的组,并查看是否有任何组属于该特定 OU。如果是这样,则删除所有这些组。

$results = ""

foreach ($ou in $OUs) 
{
  $users = Get-ADUser -SearchBase $ou -Filter * 
  foreach ($user in $users)
  {
      $groups = Get-ADPrincipalGroupMembership -Identity $User | ? {$_.distinguishedName -like "*OU I WANT TO REMOVE FROM*" }
      foreach($group in $groups) 
      {
         Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $group -whatif
         results += "$user removed from its Groups: $($groups | % { $_.name })\r\n"          
      }
  }
}

results | Out-File -Append C:\temp\new.txt

$groups 将有这种格式的成员。您可以使用 distinctName 作为过滤器类型,并使用“OU=Groups,DC=this,DC=com”之类的东西,而不是可能被认为是宽泛的“OU=Groups”。

distinguishedName : CN=GroupName,OU=****,DC=****,DC=****
GroupCategory     : Security
GroupScope        : Global
name              : <Name Of The Group>
objectClass       : group
objectGUID        : <Object Guid>
SamAccountName    : <Name Of The Group>
SID               : <SID>

我喜欢保留变量,这样我就可以使用它们来记录正在执行的更改。

注意:出于测试原因,我曾经-whatif确保它不会做您打算做的事情。Remove-ADPrincipalGroupMembership还用一组更新用户。

另一种解决方法

foreach ($ou in $OUs) 
{
  $users = Get-ADUser -SearchBase $ou -Filter * 
  $groups = Get-ADGroup -Filter * -SearchBase $DecomOUGROUP
  foreach($group in $groups) {
    Remove-ADGroupMember -Identity $group -Members $users -ErrorAction SilentlyContinue
  }
}

推荐阅读