Friday, August 19, 2022

Moving AD accounts to the different OUs based on security group membership

We've been using powershell to check for "stale" accounts, ie. haven't been logged on for 30+ days, and disabling them.  If the user requests to be enabled and becomes "active" again, another PS moves them back to the OU they are supposed to be in.  However, I recently found out that some users should be placed in different OUs based on work location or status.  Anyway, below is what I created to fix that.


    foreach($usr in $usrlist){
        write-host $usr.'Logon Name'
        Write-Host $usr.'Canonical Name'
        if ( Get-ADGroupMember -Identity "Secgroup1" | Where-Object {$_.SamAccountName -eq $usr.'logon name'} ) 
        {
            $TargetOU = "OU=Secgroup1,OU=ABC,DC=acme,DC=com"
            Get-ADGroupMember -Identity "Secgroup1" | Where-Object {$_.SamAccountName -eq $usr.'logon name'} | Move-ADObject -TargetPath $TargetOU -Verbose
        }
        elseif ( Get-ADGroupMember -Identity "Secgroup2" | Where-Object {$_.SamAccountName -eq $usr.'logon name'} ) 
        {
            $TargetOU = "OU=Secgroup2,OU=ABC,DC=acme,DC=com"
            Get-ADGroupMember -Identity "Secgroup2" | Where-Object {$_.SamAccountName -eq $usr.'logon name'} | Move-ADObject -TargetPath $TargetOU -Verbose
        } else {
            $TargetOU = "OU=Default,OU=ABC,DC=acme,DC=com"
            Get-ADUser $usr.'Logon Name' | Move-ADObject -TargetPath $TargetOU -Verbose
        }
    }

Hope you find that useful.

No comments:

Post a Comment