Private/Storage/ActiveDirectory/Set-PukAdRecord.ps1

function Set-PukAdRecord {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [string]$AttributeName,

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

        [Parameter(Mandatory)]
        [psobject]$Record,

        [string]$Server,

        [int]$MaxAttributeValueLength = 1024,

        [switch]$Force
    )

    Import-PukActiveDirectoryModule

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

    $user = Get-ADUser @getAdUserParams

    if (-not [string]::IsNullOrEmpty($user.$AttributeName) -and -not $Force) {
        throw "A record for '$($Record.DistinguishedName)' already exists in attribute '$AttributeName'. Use -Force to overwrite."
    }

    if (-not $PSCmdlet.ShouldProcess($Record.DistinguishedName, 'Set PWSHPUKMGT Active Directory record')) {
        return
    }

    $encryptedValue = Protect-PukAdAttributeValue -InputObject ([PSCustomObject]@{ SerialNumber = $Record.SerialNumber; Puk = $Record.Puk }) -Certificate $Certificate

    if ($encryptedValue.Length -gt $MaxAttributeValueLength) {
        throw "The encrypted value for '$($Record.DistinguishedName)' is $($encryptedValue.Length) characters, which exceeds the configured 'hosting.activeDirectory.maxAttributeValueLength' of $MaxAttributeValueLength for attribute '$AttributeName'. This can happen with unusually long serial numbers, or if '$AttributeName' has a smaller schema limit than configured."
    }

    $setAdUserParams = @{
        Identity    = $Record.DistinguishedName
        Replace     = @{ $AttributeName = $encryptedValue }
        ErrorAction = 'Stop'
    }
    if ($Server) { $setAdUserParams.Server = $Server }

    Set-ADUser @setAdUserParams
}