powershellactive-directorymemberof

Powershell Script to search specific OU in AD and find disabled users that is member of a group


I'm trying to write a script to find disabled users that is member of one or more groups in a specific OU in AD. It will then remove all the groups for all the disabled users. I found this script which removes all groups from users in a csv file, but as i'm looking to run this as a scheduled task I prefer not to process users that already had their groups removed without having to move them to a different OU.

Import-Csv $csvFile | ForEach-Object {
    # Disable the account
    Disable-ADAccount -Identity $_.samAccountName
    # Retrieve the user object and MemberOf property
    $user = Get-ADUser -Identity $_.samAccountName -Properties MemberOf
    # Remove all group memberships (will leave Domain Users as this is NOT in the MemberOf property returned by Get-ADUser)
    foreach ($group in ($user | Select-Object -ExpandProperty MemberOf))
    {
        Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
    }
}

Any idea on how to filter out the users with more then one group? I'm using this script to export disabled users that has not logged on for 60 days:

Get-QADUser -searchRoot $OuDomain -searchScope OneLevel -InactiveFor 61 -NotLoggedOnFor 61 -disabled -sizelimit 0

Thx


Solution

  • You seem to have filter by ou part down which is good. You have some thoughts in the beginning of you post but the only actual question is how to filter out the users with more then one group. Not sure if that is a typo or not but I read that as checking the count of groups a user has. A more realistic interpretation of that is filter users that could have at least one of a list of groups. I'm going to cover both.

    The Count

    I'm sure this is not what you want but just want to cover the base. The following would also work in a Where-Object clause

    If((get-aduser $user -Properties MemberOf).MemberOf.Count -gt 0){Process...}
    

    Multiple Groups

    I'm sure this was your intention. Locate users that could contain one of serveral groups. This is best handled with regex.

    $groupsFilter = "citrix_GateKeeper","barracuda_spam_alerts"
    $groupsFilter = "($($groupsFilter -join '|'))"
    # $groupsFilter in this example is: (citrix_GateKeeper|barracuda_spam_alerts)
    
    If(((Get-ADUser $user -Properties MemberOf).MemberOf) -match $groupsFilter){Process....}
    

    Create a regex match string based on a string array of multiple groups. If $user is a member of either of those groups then true would be returned.

    If nothing here is of any use to you then I would suggest making your question clearer. Hopefully this helps.