public/AzureAD/Clear-AzureADUserImmutableId.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<#
    .EXTERNALHELP ..\..\Clear-AzureADUserImmutableId-help.xml
#>

Function Clear-AzureADUserImmutableId {
    [cmdletbinding()] Param (
        [Parameter(Mandatory,ValueFromPipelineByPropertyName)]
        [String] $UserPrincipalName
    )

    try {
        Get-MsolDomain
    } catch {
        Connect-OnlineService -Service MsolService
    }

    try {
        if (Get-MsolUser -UserPrincipalName $UserPrincipalName -ReturnDeletedUsers) {
            # User in trash, let's restore them
            Restore-MsolUser -UserPrincipalName $UserPrincipalName
        }

        if (Get-MsolUser -UserPrincipalName $UserPrincipalName) {
            Set-MsolUser -UserPrincipalName $UserPrincipalName -ImmutableId "$null"
            Write-Output "Immutable ID has been cleared! Be sure the user isn't a member of an Active Directory OU that will cause it to be resynced and rematched to the Azure AD object via SMTP soft-matching otherwise you and I are going to become friends. :)"
        }
    } catch {
        Write-Error "Something went wrong! $_"
    }
}