Created
October 4, 2019 12:45
-
-
Save evetsleep/def1cb8eb64fd998e2230f4f1562925d to your computer and use it in GitHub Desktop.
Set OtherMails via Graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CmdletBinding()]Param( | |
[Parameter(Mandatory)] | |
[String] | |
$UserPrincipalName, | |
[Parameter(Mandatory)] | |
[AllowEmptyString()] | |
[String] | |
$NewValue, | |
[Parameter()] | |
$Tenant, | |
[Parameter()] | |
$Path = '{0}\credential.clixml' -f $PSScriptRoot | |
) | |
# Load in the client ID and secret from the encrypted config file. | |
try { | |
$Credential = Import-Clixml -Path $Path -ErrorAction STOP | |
} | |
catch { | |
Write-Error -ErrorAction STOP -Message ('Failed to load credential file: {0}' -f $PSItem.exception.message) | |
} | |
# Get a token that we can use to make the update. | |
try { | |
$requestToken = @{ | |
Grant_Type = 'client_credentials' | |
Client_Id = $Credential.UserName | |
Client_Secret = $Credential.GetNetworkCredential().Password | |
Scope = 'https://graph.microsoft.com/.default' | |
} | |
$requestSplat = @{ | |
Uri = "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/token" | |
Method = 'POST' | |
Body = $requestToken | |
ErrorAction = 'STOP' | |
} | |
$tokenResponse = Invoke-RestMethod @requestSplat | |
$tokenHeader = @{Authorization="Bearer $($tokenResponse.access_token)"} | |
} | |
catch { | |
Write-Error -ErrorAction STOP -Message ('Failed to request Graph token: {0}' -f $PSItem.exception.message) | |
} | |
# Check to make sure we can find the user first. | |
try { | |
$apiUrl = 'https://graph.microsoft.com/v1.0/users/{0}' -f $UserPrincipalName | |
$apiUrlAttributes = '{0}?$select=id,displayName,otherMails' -f $apiUrl | |
$null = Invoke-RestMethod -Headers $tokenHeader -Uri $apiUrlAttributes | |
} | |
catch { | |
Write-Error -ErrorAction STOP -Message ('Failed to query for {0}: {1}' -f $UserPrincipalName,$PSItem.exception.message) | |
} | |
# Update the current value of otherMails | |
try { | |
if ($null -like $NewValue) { | |
$attributeJSON = @{ | |
"otherMails" = @() | |
} | ConvertTo-Json | |
} | |
else { | |
$attributeJSON = @{ | |
"otherMails" = @("$NewValue") | |
} | ConvertTo-Json | |
} | |
$updateSplat = @{ | |
Headers = $tokenHeader | |
Uri = $apiUrl | |
Method = 'Patch' | |
ContentType = 'application/json' | |
Body = $attributeJSON | |
ErrorAction = 'STOP' | |
} | |
Invoke-RestMethod @updateSplat | |
} | |
catch { | |
Write-Error -ErrorAction STOP -Message ('Failed to update {0} on {1}: {2}' -f $Attribute,$UserPrincipalName,$PSItem.exception.message) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment