Home > Enterprise >  Comparing users between AAD and ADS
Comparing users between AAD and ADS

Time:04-22

I am attempting to clear out users from our School Districts ADS for some housekeeping goals we've set. Right now I have a pretty good script going that finds all deactivated student accounts and it deletes them after 30 days of being deactivated. What we have found out is that even though we delete these users from ADS, they persist for an additional 30 days in AAD in the deleted users folder. I'm trying to build a script that finds all of the users that are in the deleted users folder in AAD and then match it against the users we have in ADS, while also avoiding 2 OU's that are set to not sync student data with AAD. The first half of my script is trivial since I just need the names from the deleted users folder in AAD.

Get-MsolUser -ReturnDeletedUsers | Select DisplayName, ObjectId | Export-Csv -LiteralPath C:\Results\DeletedUsers.csv -NoTypeInformation

This gives me a csv to pull from but heres the big issue. There is no 1-to-1 selection I can make that is shared between AAD and ADS. The best thing I have found so far is to specify in my follow-up script to use the DisplayName from AAD (studentid#@domain.org) against the UserPrincipalName in ADS.

$Users = Get-Content C:\Results\DeletedUsers.csv

ForEach ($User in $Users){
        Get-ADUser -Filter * -Properties UserPrincipalName | Where { ($_.UserPrincipalName -Like $User) }
    }

The issue here is that this last half has been running for waaaaay to long and I need something a little more reliable and speedy.

CodePudding user response:

The main issue with you're code is in the foreach loop logic, you're querying for all users in your Domain per loop iteration instead of filtering for a specific user. On the other hand, it's not clear if your AD On Premises is in sync with Azure AD, why not delete the objects in AD On Prem and let them sync with Azure AD? The other issue is that you're only selecting the DisplayName and ObjectId attribtues from your Get-MsolUser query, by doing so, you're cutting off important attributes that would come in handy for searching the AD Objects in AD On Prem, for example onPremisesDistinguishedName, onPremisesSamAccountName, onPremisesUserPrincipalName.

The immediate fix to your code is this, however you should take into consideration what is mentioned above.

$Users = (Import-Csv C:\Results\DeletedUsers.csv).DisplayName
$OUsToSkip = ('OU=something,DC=something', 'OU=somethingelse,DC=something') -join '|'
foreach($User in $Users) {
    # mail attribute is equal to `$user` OR UPN is equal to `$user`
    $filter = "(|(mail=$user)(userprincipalname=$user))"
    $usr = Get-ADUser -LDAPFilter $filter
    if($usr.DistinguishedName -notmatch $OUsToSkip -and $usr) {
        $usr
    }
}
  • Related