Company Name Lookup – ForEach loops for fun and profit

By | December 4, 2020

I had to run a discovery on the company name attribute for all users on a 30k+ user tenant to see if they were properly populated and identify where we had users either with an incorrect or no Company Name attribute set.

The tenant contained users from multiple business units with their own userprincipalname domain suffix so I needed to return the data broken down by user principal name domain

I ran up this script to import a csv list of “acceptable” company names in a column labelled Company Names, identify the unique domains in the tenant then check the users using that domain suffix to see if their company name attribute was on the list of allowable items.

$domains = get-azureaddomain
$allusers = get-azureaduser -all $true -filter "UserType eq 'Member'"
$allowednames = import-csv ".\companynames.csv"
        $GlobalTotalUsers = $allusers.count
        Write-Host "Global Overall users:" $GlobalTotalUsers

        $Globalmatchedusers = $allusers | where {$_.CompanyName -in $allowednames.CompanyName -and $_.CompanyName -ne $null}
        Write-Host "Overall correct users:" $Globalmatchedusers.count -ForegroundColor Cyan
        
        $Globalunmatchedusers = $allusers | where {$_.CompanyName -notin $allowednames.CompanyName -and $_.CompanyName -ne $null}
        Write-Host "Overall incorrect users:" $Globalunmatchedusers.count  -ForegroundColor Yellow

        $Globalblankdomain = $allusers | where {$_.CompanyName -eq $null}
        Write-Host "Overall no company name specified:" $Globalblankdomain.count -ForegroundColor Red

ForEach ($domain in $domains) {
    $users = $allusers | where {$_.UserPrincipalName -like "*"+$domain.Name}
    If ($users.count -gt 0) {
        Write-Host $Domain.Name -ForegroundColor Green
        Write-Host "Total users: " $users.count -ForegroundColor Green


        
        $matchedusers = $users | where {$_.CompanyName -in $allowednames.CompanyName -and $_.CompanyName -ne $null}
        Write-Host "Total correct users:" $matchedusers.count -ForegroundColor Cyan
        If ($matchedusers.count -gt 0) {
            Write-Host "Correct Domain Names"
            $matchedusers.CompanyName | group -NoElement 
        }

        $blankdomain = $users | where {$_.CompanyName -eq $null}
        Write-Host "Total no company name specified:" $blankdomain.count -ForegroundColor Yellow

        $unmatchedusers = $users | where {$_.CompanyName -notin $allowednames.CompanyName -and $_.CompanyName -ne $null}
        Write-Host "Total incorrect users:" $unmatchedusers.count  -ForegroundColor Red
        If ($unmatchedusers.count -gt 0) {
            Write-Host "InCorrect Domain Names"
            $unmatchedusers.CompanyName | group -NoElement
        }
    } 
}

FWIW I truly love the | group function in powershell for summarising stuff nice and quick

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *