Skip to content

Instantly share code, notes, and snippets.

Embed
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 {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string] $DisplayName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string] $EmailAddress
)
[PSCustomObject]@{
PSTypeName = "GuestUser"
DisplayName = $DisplayName
EmailAddress = $EmailAddress
}
}
function Add-GuestUser {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string] $TenantId,
[Parameter(Mandatory=$true)]
[string] $AccountName,
[Parameter(Mandatory=$true)]
[string] $AccountDescription,
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[ValidateCount(1, 65535)]
[PSTypeName("GuestUser")]
[PSCustomObject[]]
$User
)
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.
Cheers,
$($adUser.DisplayName)
"@
Write-Output "Send invite to $($collectedUser.EmailAddress)"
New-AzureADMSInvitation -InvitedUserEmailAddress $collectedUser.EmailAddress -InvitedUserDisplayName $collectedUser.DisplayName `
-InviteRedirectUrl https://portal.azure.com `
-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
}
@russcam

This comment has been minimized.

Copy link
Owner Author

russcam commented Feb 26, 2019

To install

. { iwr -useb https://gist.githubusercontent.com/russcam/c763ef14fd742811a1ab5846f0e3b895/raw/31b983fb2a462b1ea710730e7f809d1261b84990/GuestUsers.ps1 } | 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.