Private/Get-CommonNameFromDN.ps1

function Get-CommonNameFromDN {
<#
.SYNOPSIS
    Retrieves the Common Name (CN) of a user given their distinguished name.
 
.PARAMETER DN
    The distinguished name (DN) of the user object.
 
.OUTPUTS
    The CN (string), or $null if not found or on error.
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$DN
    )

    process {
        try {
            $user = [ADSI]("LDAP://$DN")
            return $user.Properties["cn"][0]
        }
        catch {
            Write-Warning "Unable to retrieve CN for $DN : $($_.Exception.Message)"
            return $null
        }
    }
}