Entra / Microsoft 365 · Users & guests
Restore deleted Entra user with new UPN
Restores a soft-deleted Entra ID user account and assigns a new user principal name, reconciling proxy address conflicts when needed.
Connect & set up
Run these once per session. All scopes are read-only unless the script makes changes.
Connect-MgGraph -Scopes User.DeleteRestore.All -NoWelcome
Run it
The main script. Copy it, or download the .ps1 and run it from your console.
Connect-MgGraph -Scopes User.DeleteRestore.All$DeletedUserUPN = Read-Host "What is the UPN of the deleted user account ?"$UserDisplayName = $DeletedUserUPN.split('@')[0].Replace("."," ")$NewUserPrincipalName = Read-Host "What is the new UPN for the restored account ?"$CheckAccount = Get-MgUser -UserId $NewUserPrincipalName -ErrorAction SilentlyContinueIf ($CheckAccount) {Write-Host "The new UPN is already in use. Please choose another"Break}$Headers = @{}$Headers.Add("consistencylevel","eventual")$NewUPNDetails = @{}$NewUPNDetails.Add("newUserPrincipalName",$NewUserPrincipalName)$NewUPNDetails.Add("autoReconcileProxyConflict",$true)# Attempt to find the deleted object - for whatever reason startsWith doesn't work$DeletedObject = Get-MgDirectoryDeletedItemAsUser -Filter "endsWith(UserPrincipalName,'$DeletedUserUPN')" -Headers $Headers -CountVariable DeletedCountIf ($DeletedObject) {Write-Host "Restoring Object with new User principal Name"$Status = Restore-MgBetaDirectoryDeletedItem -DirectoryObjectId $DeletedObject.Id -BodyParameter $NewUPNDetailsIf ($Status) {Write-Host ("Account restored for {0} with UPN using {1}" -f $UserDisplayName, $NewUserPrincipalName)}}
Attribution
Author
Office365itpros