Batch-inviting users with Powershell to Azure Active Directory

The script below invites users to Azure Active Directory, and the list of users is contained within invite.txt text file (each line - email address). Unfortunately az cli does not have this capability and the only way you can do that from a script is using AzureADPreview module. Unfortunately, this module also only works in Windows Powershell (does not work on Powershell Core on Windows).

# Import-Module AzureADPreview

# Connect-AzureAD -TenantId ...

# fetch all users first
$allUsers = Get-AzureADUser -All $True
# get emails only
$allEmails = $allUsers | Select-Object -ExpandProperty Mail

# read invite.txt - this contains list of emails to invite
$toInvite = Get-Content .\invite.txt
$notInvited = $toInvite | Where-Object { -not ($allEmails -contains $_) }

Write-Host "to invite: $($toInvite.Count), not invited yet: $($notInvited.Count)"

$invited = @()

foreach($ni in $notInvited) {
    Write-Host $ni
    $namePart = ($ni -split "@")[0]
    $firstLast = $namePart -split "\."
    $first = $firstLast[0] -replace '[^a-zA-Z-]', ''
    $last = $firstLast[1] -replace '[^a-zA-Z-]', ''

    Write-Host "Inviting $first $last ($ni)"

    $messageInfo = New-Object Microsoft.Open.MSGraph.Model.InvitedUserMessageInfo
    $messageInfo.customizedMessageBody = "You are so special!"

    New-AzureADMSInvitation `
        -InvitedUserDisplayName "$first $last" `
        -InvitedUserEmailAddress "$ni" `
        -SendInvitationMessage $true `
        -InviteRedirectUrl "any url users will be redirected to after invitation." `
        -InvitedUserMessageInfo $messageInfo

    $invited += $ni

Write-Host "invited users ($($invited.Length)):"
foreach($i in $invited) {
    Write-Host $i

Have a question⁉ Contact me.