Skip to content

Restore-MsOUser

MSOnline: Restore a deleted Azure AD user

#Requires -Version 5.1

[CmdletBinding()]
Param(
    [Parameter(Mandatory = $true, ParameterSetName = 'Id')]
    [guid]$UserObjectId,
    [Parameter(Mandatory = $true, ParameterSetName = 'Name')]
    [string]$UserName,
    [Parameter(ParameterSetName = 'Name')]
    [Parameter(ParameterSetName = 'Id')]
    [guid]$TenantId
)

Process {
    try {
        if ($PSCmdlet.ParameterSetName -eq 'Id') { $user = Get-MsolUser -ObjectId $UserObjectId -TenantId $TenantId -ReturnDeletedUsers -ErrorAction Stop }
        else { $user = Get-MsolUser -SearchString $UserName -TenantId $TenantId -ReturnDeletedUsers -ErrorAction Stop | Select-Object -First 1 }

        $null = Restore-MsolUser -ObjectId $user.ObjectId -TenantId $TenantId -ErrorAction Stop

        [PSCustomObject]@{ Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'; UserName = $user.UserPrincipalName; Status = "User '$($user.UserPrincipalName)' restored" }
    }
    catch { throw }
}

Unique ID of the user to restore

Display name, Sign-In Name or UPN of the user to restore

Unique ID of the tenant

An interactive directory of PowerShell scripts.