Private/Remove-UserFromGroup_ADSI.ps1

function Remove-UserFromGroup_ADSI {
<#
.SYNOPSIS
    Removes a user from an AD group using their distinguished names and ADSI.
 
.PARAMETER UserDN
    The user’s distinguished name.
 
.PARAMETER GroupDN
    The group’s distinguished name.
 
.OUTPUTS
    Returns $true if removed or already not a member, $false if failed.
#>

    param(
        [Parameter(Mandatory)][string]$UserDN,
        [Parameter(Mandatory)][string]$GroupDN
    )

    $timestamp = "[" + (Get-Date -Format "dd/MM/yy HH:mm:ss") + "]"

    try {
        $group = [ADSI]"LDAP://$GroupDN"

        if (-not $group.IsMember("LDAP://$UserDN")) {
            Write-Output "$timestamp : User is already not a member of the group."
            return $true
        }

        $group.Remove("LDAP://$UserDN")
        $group.SetInfo()

        Write-Output "$timestamp : Successfully removed user from group."
        return $true
    }
    catch {
        Write-Output "$timestamp : ERROR - Failed to remove user from group: $($_.Exception.Message)"
        return $false
    }
}