Create custom Azure AD B2B invitation

Today I want to share with you my script for creating custom Azure AD B2B invitation.

What is Azure AD B2B?
Azure AD B2B (business-to-business) allows organization which are using Azure Active Directory to cooperate with other organizations in secure way.
Companies which are using Azure AD can proivde access to applications, resources etc. to their customers and have full control on security.

Script which I prepared allows to send custom invitation to specific application.
As an input CSV file with following columns should be created and path to file should be adjusted.

To users defined in file invitation for application will be send.

Before running the script user should provide two credentials.
First for access Azure AD and the second one for mail from which invitations will be send.
Script will also ask for three variables:
GroupName – name of the group to which user will be added in order to have access to application
ProjectName – name of the project (application) to which will have an access
ProjectURL – link to the application

Script:

$Credentials = Get-Credential
Connect-AzureAD -Credential $cred

$MailCredentials = Get-Credential
$Emails = Import-Csv -Path C:\B2Binvitation.csv

$GroupName = Read-Host -Prompt 'Provide name of the Azure AD group to which users will be added'
$ProjectName = Read-Host -Prompt 'Provide name of the project'
$ProjectUrl  = Read-host -Prompt 'Provide full url link for project'

$Group = Get-AzureADGroup -SearchString $groupname | Where-Object {$_.dirsyncenabled -eq $null}

if ($Group.count -ne 1){

    Write-Host  "Group was not found!" -ForegroundColor Red

}
else
{
    
    foreach ($email in $Emails) {

        $Name = $email.Name
        $AzureADInvitation = New-AzureADMSInvitation -InvitedUserEmailAddress $email.InvitedUserEmailAddress -InvitedUserDisplayName $Name-InviteRedirectUrl $ProjectUrl -InvitedUserMessageInfo $messageInfo -SendInvitationMessage $false

        $InvitationURL = $AzureADInvitation.InviteRedeemUrl
        $UserID= $AzureADInvitation.InvitedUser.Id
        Add-AzureADGroupMember -objectid $Group.objectid -RefObjectId $userid

        Send-MailMessage -To $result.InvitedUserEmailAddress -from $MailCredentials.UserName -Subject "Invitation to the $ProjectName"`
        -Body “Hello $Name!<br>This is your invitation to project <strong>$ProjectName</strong><br><br>Click on link below to access project:<br>$InvitationURL <br>Best regards” `
        -BodyAsHtml -SmtpServer smtp.office365.com -UseSsl -Credential $MailCredentials -Port 587

    }
}

I hope it will be usefull for some of you 😉
Enjoy!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.