Windows – Active Directory Housekeeping – Remove groups from disabled users

active-directorywindows

I am struggling to find a decent way to do this. For one reason or another (not important, it is what it is) we have a rather a lot of users who are disabled but are still a member of all of their pre-disable groups. This is causing a few issues such as distribution list failures, difficulty enumerating ACL's etc.

Does anyone know of an easy way to bulk remove groups from users that are disabled? For ease, they all exist in one container now so if its something that can be done on container level, that's useful.
Also, I know we could delete the accounts, but for auditing and cross linking with our HR system, that is not possible.

Best Answer

This sample batch file will do what you're asking. You'll need to edit the dsquery command to use your specific StartNode OU -- The OU=SomeOU,DC=example,DC=com bit:

@ECHO OFF
REM Get list of disabled users in the domain
FOR /F "usebackq delims=;" %%A IN (`dsquery user "OU=SomeOU,DC=example,DC=com" -disabled -limit 0`) DO ( 
    echo User: %%A
    REM Enumerate user's group memberOf, exclude "Domain Users" group
    FOR /F "usebackq delims=;" %%B IN (`dsget user %%A -memberof ^| find /V "Domain Users"`) DO (
        ECHO Group: %%B
        REM Remove user %%A from Group %%B
        dsmod group %%B -rmmbr %%A
    )
)