Private/Storage/ActiveDirectory/Get-PukAdRecord.ps1

function Get-PukAdRecord {
    [CmdletBinding()]
    [OutputType([psobject])]
    param(
        [Parameter(Mandatory)]
        [string]$AttributeName,

        [Parameter(Mandatory)]
        [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,

        [string]$Server,

        [string]$SearchBase,

        [Parameter(ParameterSetName = 'ByDistinguishedName', Mandatory)]
        [string]$DistinguishedName,

        [Parameter(ParameterSetName = 'BySerialNumber', Mandatory)]
        [string]$SerialNumber
    )

    Import-PukActiveDirectoryModule

    $getAdUserParams = @{
        Properties  = @($AttributeName)
        ErrorAction = 'Stop'
    }
    if ($Server) { $getAdUserParams.Server = $Server }

    if ($PSCmdlet.ParameterSetName -eq 'ByDistinguishedName') {
        try {
            $user = Get-ADUser -Identity $DistinguishedName @getAdUserParams
        }
        catch {
            return $null
        }

        $encryptedValue = $user.$AttributeName
        if ([string]::IsNullOrEmpty($encryptedValue)) {
            return $null
        }

        $decrypted = Unprotect-PukAdAttributeValue -Value $encryptedValue -Certificate $Certificate
        return [PSCustomObject]@{
            DistinguishedName = $user.DistinguishedName
            SerialNumber      = $decrypted.SerialNumber
            Puk               = $decrypted.Puk
        }
    }

    $allRecordsParams = @{ AttributeName = $AttributeName; Certificate = $Certificate }
    if ($Server) { $allRecordsParams.Server = $Server }
    if ($SearchBase) { $allRecordsParams.SearchBase = $SearchBase }

    $match = Get-PukAdAllRecords @allRecordsParams | Where-Object { $_.SerialNumber -eq $SerialNumber } | Select-Object -First 1
    return $match
}