Private/Add-SshImportIdAuthorizedKey.ps1

function Add-SshImportIdAuthorizedKey {
    <#
    .SYNOPSIS
        Appends new (de-duplicated) public keys to an authorized_keys file.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([pscustomobject])]
    param(
        [Parameter(Mandatory)]
        [string] $Path,

        [Parameter(Mandatory)]
        [string[]] $KeyLine,

        [Parameter(Mandatory)]
        [string] $Tag
    )

    $existingLines = @()
    if (Test-Path -Path $Path) {
        $existingLines = @(Get-Content -Path $Path -ErrorAction SilentlyContinue)
    }
    $existingKeyMaterial = [System.Collections.Generic.HashSet[string]]::new()
    foreach ($line in $existingLines) {
        if ($line -match '(?<type>ssh-\S+|ecdsa-\S+|sk-\S+)\s+(?<data>\S+)') {
            [void]$existingKeyMaterial.Add("$($Matches.type) $($Matches.data)")
        }
    }

    $toAdd = @()
    $skipped = @()

    foreach ($line in $KeyLine) {
        if ($line -notmatch '^(?<type>\S+)\s+(?<data>\S+)(?:\s+(?<comment>.*))?$') {
            continue
        }
        $material = "$($Matches.type) $($Matches.data)"

        if ($existingKeyMaterial.Contains($material)) {
            $skipped += $line
            continue
        }

        $toAdd += "$material # ssh-import-id $Tag"
        [void]$existingKeyMaterial.Add($material)
    }

    $added = @()
    if ($toAdd.Count -gt 0 -and $PSCmdlet.ShouldProcess($Path, "Append $($toAdd.Count) key(s) ($Tag)")) {
        $dir = Split-Path -Parent $Path
        if (-not (Test-Path -Path $dir)) {
            New-Item -ItemType Directory -Path $dir -Force | Out-Null
        }
        if (-not (Test-Path -Path $Path)) {
            New-Item -ItemType File -Path $Path -Force | Out-Null
        }
        Add-Content -Path $Path -Value $toAdd
        $added = $toAdd
    }

    [pscustomobject]@{
        Added   = $added
        Skipped = $skipped
    }
}