Skip to content

Remove-MsOUser

MSOnline: Remove a user from Azure AD

#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')]
    [switch]$RemoveFromRecycleBin,
    [Parameter(ParameterSetName = 'Name')]
    [Parameter(ParameterSetName = 'Id')]
    [guid]$TenantId
)

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

        $null = Remove-MsolUser -ObjectId $user.ObjectId -TenantId $TenantId -RemoveFromRecycleBin:$RemoveFromRecycleBin -Force -ErrorAction Stop

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

Unique ID of the user to remove

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

Off

Permanently remove from the recycle bin

Unique ID of the tenant

An interactive directory of PowerShell scripts.