Instantly share code, notes, and snippets.

Embed
What would you like to do?
FIM/MIM Azure AD B2B Inviter PowerShell Management Agent
param
(
$username,
$password,
$ExportType
)
begin
{
$DebugFilePath = "C:\PROGRA~1\MICROs~2\2010\SYNCHR~1\EXTENS~2\AzureA~3\Debug\AADB2BExport.txt"
if(!(Test-Path $DebugFilePath))
{
$DebugFile = New-Item -Path $DebugFilePath -ItemType File
}
else
{
$DebugFile = Get-Item -Path $DebugFilePath
}
"Starting Import as : " + $OperationType + (Get-Date) | Out-File $DebugFile -Append
# Adding the AD library to your PowerShell Session.
Add-Type -Path 'C:\Program Files\WindowsPowerShell\Modules\AzureADPreview\2.0.0.52\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# This is the tenant id of you Azure AD. You can use tenant name instead if you want.
$tenantID = "mydomain.onmicrosoft.com"
$authString = "https://login.microsoftonline.com/$tenantID"
# The resource URI for your token.
$resource = "https://graph.microsoft.com/"
# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
# ********************** Authentication to Azure ***************************
# The username must be MFA disabled user Admin at least, and must not be a live id.
# Create a client credential with the above common client id, username and password from the Connectivity tab on the MA.
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $Username,$Password
# Create a authentication context with the above authentication string.
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
# Acquire access token from server.
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# Use the access token to setup headers for your http request.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
$headers = @{"Authorization"=$authHeader; "Content-Type"="application/json"}
$invitationURL = "https://graph.microsoft.com/v1.0/invitations"
$invitationRedirectURL = "http://www.mydomain.com"
"Starting Export : " + (Get-Date) | Out-File $DebugFile -Append
"ExportType : $ExportType " | Out-File $DebugFile -Append
}
process
{
$error.clear()
$errorstatus = "success"
$errordetails = $null
$inviteEmailAddress = $null
$Identifier = $_.'[Identifier]'
$objectGuid = $_.'[DN]'
$id = $_.'[Anchor]'
$_ | out-file $DebugFile -append
#Supported ChangeType is Replace
if ($_.'[ObjectModificationType]' -eq 'Replace') {
$errorstatus = "success"
$errorname = $null
$errordetails = $null
[boolean]$exportNamingData = $false
$userIDurl = $null
#Loop through changes and update parameters
foreach ($can in $_.'[ChangedAttributeNames]') {
Write-output "Changed Attrib: $can" | out-file $DebugFile -append
if ( $can -eq 'AADGivenName'){$AADGivenName = $_.'AADGivenName'; $exportNamingData = $true }
if ( $can -eq 'AADSurname'){$AADSurname = $_.'AADSurname'; $exportNamingData = $true}
if ( $can -eq 'AADDisplayName'){$AADDisplayName = $_.'AADDisplayName'; $exportNamingData = $true}
}
# Export Naming info if there are changes
if ($exportNamingData -eq $true){
"update $($id)" | out-file $DebugFile -append
$body = @{
givenName = $AADGivenName
surname = $AADSurname
displayName = $AADDisplayName
}
$body = $body | ConvertTo-Json
# Update User by ID
$userIDurl = "https://graph.microsoft.com/v1.0/users/$($_.objectID)"
$userIDurl | out-file $DebugFile -append
# Update User
try{
Invoke-RestMethod -Method Patch -Headers @{
Authorization = $authenticationResult.CreateAuthorizationHeader()
'Content-Type' = "application/json"
} -body $body -Uri ($userIDurl -f $authenticationResult.TenantId)
} catch {
"Problem updating user $($id) " | Out-File $DebugFile -Append
"**Error Status Code** " + $_.Exception.Response.StatusCode.value__ | Out-File $DebugFile -Append
"**Error Status Description** " + $_.Exception.Response.StatusDescription | Out-File $DebugFile -Append
$errordetails = $_.Exception.Response.StatusDescription
$errorname = $_.Exception.Response.StatusCode.value__
}
}
}
#Supported ChangeType is Add
if ($_.'[ObjectModificationType]' -eq 'Add') {
$errorstatus = "success"
$errorname = $null
$errordetails = $null
# Invite the the B2B User
if(!$inviteEmailAddress){
$inviteEmailAddress = $_.AADMail
$inviteBody = @{"invitedUserEmailAddress" = $inviteEmailAddress; "inviteRedirectUrl"= $invitationRedirectURL; "sendInvitationMessage"= $false}
$inviteBody = $inviteBody | ConvertTo-Json
try{
# Invite
$invite = Invoke-RestMethod -Method POST -Headers @{
Authorization = $authenticationResult.CreateAuthorizationHeader()
'Content-Type' = "application/json"
} -Uri ($invitationURL -f $authenticationResult.TenantId) -Body $inviteBody
} catch {
"Problem inviting user $($inviteEmailAddress) " | Out-File $DebugFile -Append
"**Error Status Code** " + $_.Exception.Response.StatusCode.value__ | Out-File $DebugFile -Append
"**Error Status Description** " + $_.Exception.Response.StatusDescription | Out-File $DebugFile -Append
$errordetails = $_.Exception.Response.StatusDescription
$errorname = $_.Exception.Response.StatusCode.value__
}
}
}
#Return the result to the MA
$obj = @{}
$obj.Add("[Identifier]",$Identifier)
if($errorname){$obj.Add("[ErrorName]",$errorname)}else{$obj.Add("[ErrorName]","success") }
if($errordetails){$obj.Add("[ErrorDetail]",$errordetails) }
$obj
}
end
{
#All done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment