Script Repository


Change user ID in Office 365

November 15, 2018
2735

You can use the script in Business Rules, Custom Commands and Scheduled Tasks to update Office 365 user IDs. To add the script to your rule, command or task, use the Run a program or PowerShell script action.

Parameter:

  • $newID - specifies a template for the new Office 365 ID. In the template, you can use value references. When the script runs, the value references are replaced with property values of a user on which the rule, command or task is executed.

Adaxes versions 2018.1 and earlier

Edit Remove
PowerShell
$newID = "%firstname:lower%.%lastname:lower%@domain.com" # TODO: modify me

# Get Office 365 Object ID
try
{
    $objectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")    
}
catch
{
    $Context.LogMessage("The user doesn't have an Office 365 account", "Warning")
    return
}

# Get Office 365 Tenant credentials
$office365Cred = $Context.GetOffice365Credential()

$scriptBlock = {
    param ($objectId, $newID, $office365Cred)
    Import-Module MSOnline
    
    Connect-MsolService -Credential $office365Cred
        
    # Check whether the Office 365 User ID differs from the new ID
    $userO365 = Get-MsolUser -ObjectId $objectId 
    $o365Username = $userO365.UserPrincipalName

    if ($o365Username -ieq $newID)
    {
        return # No changes needed
    }

    # Change the Office 365 User ID
    Set-MsolUserPrincipalName -ObjectId $objectId -NewUserPrincipalName $newID
    
}

# Start Windows PowerShell as a separate process and run the script in that process
$job = Start-Job -ScriptBlock $scriptBlock -ArgumentList $objectId.ToString(), $newID, $office365Cred
Wait-Job -Job $job

# Get output from external process
Receive-Job -Job $job
$Context.LogMessage("Office 365 User ID was changed to: $newID", "Information")

Adaxes versions 2018.2 and later

For the script to work, you need to install Microsoft Azure Active Directory Module for Windows PowerShell on each computer where Adaxes service is running.

Edit Remove
PowerShell
$newID = "%firstname:lower%.%lastname:lower%@example.com" # TODO: modify me

# Get the Office 365 object ID
try
{
    $objectId = [GUID]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    $Context.LogMessage("The user doesn't have an Office 365 account", "Warning")
    return
}

# Connect to Office 365
$Credential = $Context.GetOffice365Credential()
Connect-MsolService -Credential $Credential

# Check whether the Office 365 User ID differs from the new ID
$userO365 = Get-MsolUser -ObjectId $objectId
$o365Username = $userO365.UserPrincipalName

if ($o365Username -ieq $newID)
{
    return # No changes needed
}

# Change the Office 365 User ID
Set-MsolUserPrincipalName -ObjectId $objectId -NewUserPrincipalName $newID
$Context.LogMessage("Office 365 User ID has been changed to: $newID", "Information")

Comments ( 0 )
No results found.
Leave a comment