Skip to content

Remove-O365User

Azure AD: Removes a user from the tenant

#Requires -Version 5.1
#Requires -Modules AzureAD

[CmdletBinding(DefaultParameterSetName = "UserName")]
Param(
    [Parameter(Mandatory = $true, ParameterSetName = "UserObjectId")]
    [guid]$UserObjectId,

    [Parameter(Mandatory = $true, ParameterSetName = "UserName")]
    [string]$UserName
)

Process {
    try {
        if ($PSCmdlet.ParameterSetName -eq "UserObjectId") {
            $usr = Get-AzureADUser -ObjectId $UserObjectId -ErrorAction Stop | Select-Object ObjectID, DisplayName
        }
        else {
            $usr = Get-AzureADUser -All $true -ErrorAction Stop | Where-Object { ($_.DisplayName -eq $UserName) -or ($_.UserPrincipalName -eq $UserName) } | Select-Object ObjectID, DisplayName
        }

        if ($null -eq $usr) { throw "User not found" }

        $null = Remove-AzureADUser -ObjectId $usr.ObjectID -ErrorAction Stop

        [PSCustomObject]@{
            Timestamp   = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            Status      = "Success"
            DisplayName = $usr.DisplayName
            ObjectId    = $usr.ObjectID
            Message     = "User '$($usr.DisplayName)' removed"
        }
    }
    catch { throw }
}

Unique object ID of the user to remove

Display name or user principal name of the user to remove

An interactive directory of PowerShell scripts.