top of page
Search

Matching some AAD and AD accounts

  • ToddimusPrime
  • Aug 11, 2021
  • 2 min read

Our Office 365 setup is fairly typical with AD accounts being synced to AAD. However, for some reason there are a bunch of cloud-only accounts up in AAD that seem to match accounts that are also in AD. I have no idea why these accounts exist... I've been tasked with cleaning this up and needed a way to compare the cloud-only accounts to the on-prem accounts to see what matches up.


I've tried to put comments in the script to explain what's going on with it, but basically you need to first export the cloud-only users' email addresses from AAD and save them into a text file with one item per line. The rest is done with a bunch of foreach loops, Get-ADUser cmdlets, splitting strings at the @ character, and the real hero of the day: using the -contains parameter to compare two arrays.



#Initialize some arrays
$theADaccounts = @()
$theAADaccounts = @()
$matchedAccounts = @()

#Get all of the UPNs in AD, then split them at @ to get just the first portion of the UPN
$UPNs = Get-ADUser -filter * | Select-Object userprincipalname
foreach ($UPN in $UPNs)
{
    try
    {
        $doodad = $UPN.userprincipalname #need to convert the object into a single item for the split on the next line to work
        $splitUPN = $doodad.Split("@")[0]
    }
    catch
    {
        #skip adding to the array if a weirdly formatted UPN is found in AD
    }
    finally
    {
        $theADaccounts += $splitUPN
    }
}

#emails.txt is an export of all AAD cloud-only users' email addresses.  Get those emails, then split them at @ to get just the first portion of the email address.
$emails = get-content "<path to emails.txt goes here>"
foreach ($email in $emails)
{
    $upn2 = $email.Split("@")[0]
    $theAADaccounts += $upn2
}

#Compare the split UPN from AD with the split email address from AAD.  Add any matches to an array
foreach ($AADaccount in $theAADaccounts)
{
    if ($theADaccounts -contains $AADaccount)
    {
        $matchedAccounts += $AADaccount
    }
}

#Take the array of matches, then search for UPNs in AD that contain the split string.  Output the account name along with the enabled status
foreach ($matchedAccount in $matchedAccounts)
{
    $searchString = "$matchedAccount" + "*"
    get-aduser -Filter 'UserPrincipalName -like $searchString' | Select-Object name,enabled
}

Comments


©2021 by ToddimusPrime

bottom of page