Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
PowerShell script module for creating and adding guest users to Azure AD
New-Module -Name GuestUsers -Scriptblock {
$modules = Get-Module -ListAvailable AzureAD*
if ($null -eq $modules) {
Write-Output "Install AzureADPreview module"
Install-Module AzureADPreview
elseif (($modules | ?{ $_.Name -eq "AzureAD" }).Count -eq 1) {
Write-Output "Uninstall AzureAD module and install AzureADPreview module"
Uninstall-Module AzureAD
Install-Module AzureADPreview
function New-GuestUser {
param (
[string] $DisplayName,
[string] $EmailAddress
PSTypeName = "GuestUser"
DisplayName = $DisplayName
EmailAddress = $EmailAddress
function Add-GuestUser {
param (
[string] $TenantId,
[string] $AccountName,
[string] $AccountDescription,
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[ValidateCount(1, 65535)]
Begin {
$collectedUsers = @()
Process {
$collectedUsers += $User
End {
Write-Output "Connect to Azure AD with Tenant ID $TenantId"
$account = Connect-AzureAD -TenantId $TenantId
$adUser = Get-AzureADUser -SearchString $account.Account.Id
foreach ($collectedUser in $collectedUsers) {
$existingUser = Get-AzureADUser -SearchString $collectedUser.EmailAddress
if ($null -eq $existingUser -or $existingUser.UserState -eq "PendingAcceptance") {
$messageInfo = New-Object Microsoft.Open.MSGraph.Model.InvitedUserMessageInfo
$messageInfo.CustomizedMessageBody = @"
Hey $($collectedUser.DisplayName),
Please accept this invitation to join the $accountName. This account is used for $accountDescription.
Write-Output "Send invite to $($collectedUser.EmailAddress)"
New-AzureADMSInvitation -InvitedUserEmailAddress $collectedUser.EmailAddress -InvitedUserDisplayName $collectedUser.DisplayName `
-InviteRedirectUrl `
-InvitedUserMessageInfo $messageInfo -SendInvitationMessage $true | Out-Null
Write-Output "Invite sent to $($collectedUser.EmailAddress)"
else {
Write-Output "User $($collectedUser.DisplayName) ($($collectedUser.EmailAddress)) already exists with state $($existingUser.UserState)"
Export-ModuleMember New-GuestUser,Add-GuestUser

This comment has been minimized.

Copy link
Owner Author

russcam commented Feb 26, 2019

To install

. { iwr -useb } | iex;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.