Share via

Removing disabled user-objects from Distribution groups but with Exclusion

misyw 1 Reputation point
2022-05-26T22:10:48.017+00:00

Hi all,

I have the script to remove disabled users from all distribution groups in a specific OU. However, I could not figure out how to add an exception where if the disabled user is a member of a specific security group (aka "ExcludeGroup") then do no remove the disabled user from those distribution groups.

Here is the script I'm using:

$searchOU = 'OU=Distribution Lists,DC=companyA,DC=com'
$groups = Get-ADGroup -Filter{GroupCategory -eq "Distribution"} -SearchBase $searchOU | select -ExpandProperty Name

foreach($group in $groups){
Get-ADGroupMember -Identity $group -Recursive | Get-ADUser | where{($.Enabled -eq $false) -and ($.memberof -notlike 'ExcludeGroup')} |
foreach{
$uname = $_.samaccountname
$gname = $($group)
Write-Host "Removing $($uname) from $($gname)" -Foreground Yellow
Remove-ADGroupMember -Identity $gname -Member $uname -Confirm:$false
}
}

If I remove the chunk where I adding my exception in line 4 then the script works
-and ($_.memberof -notlike 'ExcludeGroup')}

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

2 answers

Sort by: Most helpful
  1. Limitless Technology 45,241 Reputation points
    2022-06-01T07:43:14.867+00:00

    Hello Misyw,

    This is because before the -notlike there is not a defined property, thus can't exclude something from a null reference.

    You will need to define first the property as membership, then specify the ones no in the group. Like this:

    -properties memberof | Where-Object {!($_.memberof -like "ExcludeGroup")}

    You can test this with a count of users, for example:

    Get-ADUser -Filter * -properties memberof | Where-Object {!($_.memberof -like "permanent")} | measure


    --If the reply is helpful, please Upvote and Accept as answer--

    Was this answer helpful?

    0 comments No comments

  2. Newbie Jones 1,411 Reputation points
    2022-05-27T13:47:42.35+00:00

    Consider the following snippet.

    $excludedGroup = (Get-ADGroup "GroupA").distinguishedName
    
     Where-Object {$excludedGroup -NotIn $_.memberof} 
    

    You can use wildcards but I recommend using the distinguishedName to avoid any potential groups with similar names.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.