To change the mail field in Azure Active Directory using PowerShell, you'll need to use the AzureAD module or the newer Azure Active Directory PowerShell for Graph module (AzureADPreview). If you haven't installed the AzureAD or AzureADPreview module, you can install it using the following command:
Install-Module -Name AzureAD
# or for the preview version
Install-Module -Name AzureADPreview
The following example demonstrates how you can use PowerShell to change the mail field for a user in Azure Active Directory:
# Import the module
Import-Module AzureAD
# or Import-Module AzureADPreview
# Connect to Azure AD with an account that has the necessary permissions
Connect-AzureAD
# The user's Object ID or user principal name (UPN)
$userUPN = "user@domain.com"
# The new mail address you want to set
$newMail = "newemail@domain.com"
# Retrieve the user object
$user = Get-AzureADUser -ObjectId $userUPN
# Update the user's mail field
Set-AzureADUser -ObjectId $user.ObjectId -Mail $newMail
# Verify the change
Get-AzureADUser -ObjectId $userUPN | Select-Object DisplayName, Mail
Before running this script, ensure that you have the necessary permissions to update user profiles in Azure AD. Typically, you need to be a Global Administrator or User Administrator in Azure AD to perform these changes.
Note: The mail attribute is usually managed by Exchange Online and is typically read-only in Azure AD if the mailbox is hosted in Exchange Online. If you attempt to update the mail attribute and it fails, this might be the reason. If this is the case, you should use Exchange Online PowerShell to update the email address, or change it through the Exchange Admin Center (EAC) if you're using Office 365 or Microsoft 365.
Here's how you might do it through Exchange Online PowerShell, assuming you have the Exchange Online Management module installed (Install-Module -Name ExchangeOnlineManagement):
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName <your admin account>
# Set the primary email address (which will update the mail attribute in Azure AD)
Set-Mailbox -Identity $userUPN -PrimarySmtpAddress $newMail
# Verify the change
Get-Mailbox -Identity $userUPN | Select-Object DisplayName, PrimarySmtpAddress
Remember to replace <your admin account> with your actual admin user principal name and perform the necessary changes for your specific environment.