Scenario

Depending upon External Collaboration settings, B2B (or Guest) users may originate from any number of domains.

PowerShell Script

The following snippet provides a way to get the number of B2B (or Guest) users in Azure AD and the domains from which they originate.

Sample Output

Key                 Value
---                 -----
chrisdymond.org         1
chris.org              10
chris.net              13

B2B accounts: 24

Code

Note that this snippet depends upon the Azure AD or AzureADPreview PowerShell modules.

using namespace System.Collections.Generic

try {
    Get-AzureADTenantDetail | Out-Null
}
catch [Microsoft.Open.Azure.AD.CommonLibrary.AadNeedAuthenticationException] {
    Connect-AzureAD
}

$users = Get-AzureADUser -Filter "userType eq 'Guest'" -All $true
        $b2bDomains = [Dictionary[String, Int32]]::new()
        foreach ($user in $users) {
            if ($null -ne $user.Mail) {
                $b2bDomain = $user.Mail.Split('@')[1].ToLower()
            } else {
                # Mail is not always populated
                # UPN will be used to ascertain the domain
                # chris.dymond_something.com.au#EXT#@x.onmicrosoft.com
                # chris_dymond_something.com.au#EXT#@x.onmicrosoft.com
                $userPrincipalName = $user.UserPrincipalName
                $b2bDomain = ($userPrincipalName.Split('#')[0].Split('_')[$userPrincipalName.Split('#')[0].Split('_').Count - 1]).ToLower()
            }

          
            if ($b2bDomains.ContainsKey($b2bDomain)) {
                $b2bDomains[$b2bDomain]++
            }
            else {
                $b2bDomains.Add($b2bDomain, 1)
            }
        }
        $b2bDomains.GetEnumerator() | Sort-Object | Format-Table
        Write-Host "B2B accounts: $($users.Count)"
        # $b2bDomains.GetEnumerator() | Export-Csv -NoTypeInformation -Path '.YourFileName.csv'