Public/Export-NSPOutlookContactCsv.ps1

function Export-NSPOutlookContactCsv {
    <#
    .SYNOPSIS
        Converts a vCard file (Apple Contacts export) into Outlook contact-import CSV batches,
        keeping every intermediate output.
    .DESCRIPTION
        Stage 1 work\01-parsed.jsonl ConvertFrom-NSPVCard output. Reused while the source
                                               file is unchanged; -Reparse forces a new parse.
                                               -Path may also name a .jsonl file directly.
        Stage 2 work\02-mapped.csv every contact: SourceIndex plus Outlook columns
                 work\02-extras.csv each value moved to Notes or dropped, and why
                 work\02-skipped.csv cards with nothing identifying
                 work\02-possible-duplicates.csv same Name and first e-mail (reported only)
        Stage 3 OutlookContacts_NNN.csv Outlook columns only, -BatchSize rows each
                 ImportManifest.csv rows and SourceIndex range per batch

        Mapping:
        - Apple item labels (Work Fax, Mobile, Home, ...) decide the phone and address type.
        - ms-outlook: links left by an earlier Outlook sync are dropped.
        - A value with no free Outlook column is added to Notes, never dropped silently.
        - Year-less Apple birthdays (year 1604 or X-APPLE-OMIT-YEAR) go to Notes as MM/DD.
        - Company cards (X-ABShowAs:COMPANY) keep First Name empty.
        - Spouse and Anniversary use Outlook's own columns.
        - Repeated phone numbers (by digits) and e-mail addresses inside one card are collapsed.
        - Photos cannot travel in CSV and are dropped (logged).

        Existing OutlookContacts_*.csv files in -OutputDirectory are an error unless -Overwrite
        is given, because a stale extra batch would import duplicates.

        Performance note: the per-card path uses inline .NET calls; Windows PowerShell 5.1 pays
        a high price per PowerShell function call. Keep it that way when editing.
    .OUTPUTS
        One summary object: OutputDirectory, Cards, Exported, Skipped, Extras, ExtrasByReason,
        PossibleDuplicates, Batches (the manifest rows), Seconds.
    .EXAMPLE
        Export-NSPOutlookContactCsv -Path .\Contacts.vcf -OutputDirectory .\OutlookImport
    .EXAMPLE
        Export-NSPOutlookContactCsv -Path .\Contacts.vcf -OutputDirectory .\OutlookImport -BatchSize 1000 -Overwrite
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Path,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$OutputDirectory,
        [ValidateRange(1, 100000)][int]$BatchSize = 1500,
        [switch]$Reparse,
        [switch]$Overwrite
    )

    $watch = [Diagnostics.Stopwatch]::StartNew()
    $source = Get-Item -LiteralPath (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
    $null = New-Item -ItemType Directory -Force -Path $OutputDirectory
    $OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).ProviderPath
    $work = Join-Path $OutputDirectory 'work'
    $null = New-Item -ItemType Directory -Force -Path $work
    $utf8Bom = [System.Text.UTF8Encoding]::new($true)
    $utf8 = [System.Text.UTF8Encoding]::new($false)
    $lf = "`n"

    $oldBatches = @(Get-ChildItem -LiteralPath $OutputDirectory -Filter 'OutlookContacts_*.csv' -File)
    if ($oldBatches.Count -gt 0 -and -not $Overwrite) {
        throw "$($oldBatches.Count) OutlookContacts_*.csv file(s) already in $OutputDirectory. Use -Overwrite to replace them; a stale extra batch would import duplicates."
    }

    # --- Stage 1 ---------------------------------------------------------------------------------
    if ($source.Extension -ieq '.jsonl') {
        $parsedPath = $source.FullName
        Write-Verbose "Stage 1: using $parsedPath"
    } else {
        $parsedPath = Join-Path $work '01-parsed.jsonl'
        $stampPath = Join-Path $work '01-parsed.source.txt'
        $stamp = 'NSP.LogParse.vcard.1|{0}|{1}|{2}' -f $source.FullName, $source.Length, $source.LastWriteTimeUtc.Ticks
        $reuse = (-not $Reparse) -and (Test-Path -LiteralPath $parsedPath) -and (Test-Path -LiteralPath $stampPath) -and
                 ([IO.File]::ReadAllText($stampPath).Trim() -eq $stamp)
        if ($reuse) { Write-Verbose "Stage 1: reusing $parsedPath (source unchanged)" }
        else {
            $parse = ConvertFrom-NSPVCard -Path $source.FullName -OutFile $parsedPath
            [IO.File]::WriteAllText($stampPath, $stamp)
            Write-Verbose ("Stage 1: parsed {0} cards ({1} s)" -f $parse.Cards, $parse.Seconds)
        }
    }

    # --- Stage 2 ---------------------------------------------------------------------------------
    $headers = @(
        'First Name', 'Middle Name', 'Last Name', 'Title', 'Suffix', 'Name',
        'E-mail Address', 'E-mail 2 Address', 'E-mail 3 Address',
        'Mobile Phone', 'Home Phone', 'Home Phone 2', 'Business Phone', 'Business Phone 2',
        'Primary Phone', 'Company Main Phone', 'Other Phone', 'Business Fax', 'Home Fax', 'Other Fax', 'Pager',
        'Company', 'Department', 'Job Title',
        'Home Street', 'Home City', 'Home State', 'Home Postal Code', 'Home Country/Region',
        'Business Street', 'Business City', 'Business State', 'Business Postal Code', 'Business Country/Region',
        'Other Street', 'Other City', 'Other State', 'Other Postal Code', 'Other Country/Region',
        'Web Page', 'Birthday', 'Anniversary', 'Spouse', 'Notes'
    )
    $emailSlots = 'E-mail Address', 'E-mail 2 Address', 'E-mail 3 Address'
    $ignored = @{ 'VERSION' = 1; 'PRODID' = 1; 'UID' = 1; 'REV' = 1; 'X-ABUID' = 1; 'X-ABSHOWAS' = 1; 'X-ABADR' = 1 }

    function ConvertTo-OutlookDate([string]$Value, [string]$Parameters) {
        # Rare (BDAY, X-ABDATE), so a function call is acceptable. Returns @(csvValue, noteText).
        if ($Value -match '^--(\d{2})-?(\d{2})$') { return @('', ('{0}/{1} (no year)' -f $Matches[1], $Matches[2])) }
        if ($Value -match '^(\d{4})-?(\d{2})-?(\d{2})(T.*)?$') {
            if ($Matches[1] -eq '1604' -or $Parameters -match '(?i)X-APPLE-OMIT-YEAR') { return @('', ('{0}/{1} (no year)' -f $Matches[2], $Matches[3])) }
            return @(('{0}/{1}/{2}' -f $Matches[2], $Matches[3], $Matches[1]), '')
        }
        @('', $Value)
    }

    $extras = [System.Collections.Generic.List[object]]::new()
    $skipped = [System.Collections.Generic.List[object]]::new()
    $mappedLines = [System.Collections.Generic.List[string]]::new()
    $batchLines = [System.Collections.Generic.List[string]]::new()
    $sourceIndex = [System.Collections.Generic.List[int]]::new()
    $duplicateKeys = @{}
    $kindCache = @{}
    $csvLine = [System.Text.StringBuilder]::new()

    # -InputObject, not the pipeline: Windows PowerShell 5.1 would pass the array as one object.
    # Assign first, then @(): wrapping the call directly would nest the array on 5.1.
    $parsedCards = ConvertFrom-Json -InputObject ('[' + ((@([IO.File]::ReadAllLines($parsedPath, $utf8)) -ne '') -join ',') + ']')
    $cards = @($parsedCards)
    Write-Verbose ("Stage 2: loaded {0} cards ({1:n1} s)" -f $cards.Count, $watch.Elapsed.TotalSeconds)

    foreach ($card in $cards) {
        $idx = [int]$card.index
        $row = @{}
        $more = [System.Collections.Generic.List[string]]::new()
        $notes = [System.Collections.Generic.List[string]]::new()
        $emails = [System.Collections.Generic.List[object]]::new()
        $phones = [System.Collections.Generic.List[object]]::new()
        $addresses = [System.Collections.Generic.List[object]]::new()
        $urls = [System.Collections.Generic.List[string]]::new()
        $cardExtras = [System.Collections.Generic.List[object]]::new()
        $fullName = ''
        $isCompany = $false

        foreach ($p in $card.properties) {
            $n = $p.name
            $v = $p.value
            if ($n -eq 'TEL' -or $n -eq 'ADR') {
                # An Apple label that names a kind wins over TYPE parameters. Cached per label and types.
                $kindKey = $p.label + '|' + ($p.types -join ',')
                $kinds = $kindCache[$kindKey]
                if ($null -eq $kinds) {
                    $kindList = [System.Collections.Generic.List[string]]::new()
                    $label = $p.label.ToLowerInvariant()
                    if ($label) {
                        if ($label -match 'fax') { $kindList.Add('FAX') }
                        if ($label -match 'work|business|office') { $kindList.Add('WORK') }
                        if ($label -match 'home') { $kindList.Add('HOME') }
                        if ($label -match 'mobile|cell|iphone') { $kindList.Add('CELL') }
                        if ($label -match 'pager') { $kindList.Add('PAGER') }
                        if ($label -match 'main') { $kindList.Add('MAIN') }
                        if ($label -match 'other') { $kindList.Add('OTHER') }
                    }
                    if ($kindList.Count -eq 0) { foreach ($t in $p.types) { if ($t -eq 'IPHONE' -or $t -eq 'MOBILE') { $kindList.Add('CELL') } else { $kindList.Add($t) } } }
                    $kinds = $kindList.ToArray()
                    $kindCache[$kindKey] = $kinds
                }
                if ($n -eq 'TEL') { $phones.Add(@($p, $kinds)) } else { $addresses.Add(@($p, $kinds)) }
                continue
            }
            switch ($n) {
                'FN' { $fullName = $v }
                'N' {
                    $a = @($p.parts)
                    $f = 'Last Name', 'First Name', 'Middle Name', 'Title', 'Suffix'
                    for ($m = 0; $m -lt 5 -and $m -lt $a.Count; $m++) { $row[$f[$m]] = ([string]$a[$m]).Trim() }
                }
                'X-ABSHOWAS' { if ($v -ieq 'COMPANY') { $isCompany = $true } }
                'EMAIL' { $emails.Add($p) }
                'ORG' {
                    $o = @($p.parts)
                    $row['Company'] = ([string]$o[0]).Trim()
                    if ($o.Count -gt 1) { $row['Department'] = ([string]$o[1]).Trim() }
                }
                'TITLE' { $row['Job Title'] = $v }
                'NOTE' { if ($v.Trim()) { $notes.Add($v) } }
                'URL' {
                    if ($v.StartsWith('ms-outlook:', [StringComparison]::OrdinalIgnoreCase)) { $cardExtras.Add(@('URL', $p.label, $v, 'Dropped', 'Outlook sync link')) }
                    elseif ($v) { $urls.Add($v) }
                }
                'BDAY' {
                    $date = ConvertTo-OutlookDate $v $p.parameters
                    $row['Birthday'] = $date[0]
                    if ($date[1]) { $more.Add("Birthday: $($date[1])") }
                }
                'X-ABDATE' {
                    $label = $p.label
                    if ($label.StartsWith('_$!<') -and $label.EndsWith('>!$_')) { $label = $label.Substring(4, $label.Length - 8) }
                    $date = ConvertTo-OutlookDate $v $p.parameters
                    if ($label -ieq 'Anniversary' -and $date[0] -and -not $row['Anniversary']) { $row['Anniversary'] = $date[0] }
                    else { $more.Add("$(if ($label) { $label } else { 'Date' }): $(if ($date[0]) { $date[0] } else { $date[1] })") }
                }
                'X-ABRELATEDNAMES' {
                    $label = $p.label
                    if ($label.StartsWith('_$!<') -and $label.EndsWith('>!$_')) { $label = $label.Substring(4, $label.Length - 8) }
                    if ($label -ieq 'Spouse' -and -not $row['Spouse']) { $row['Spouse'] = $v }
                    else { $more.Add("$(if ($label) { $label } else { 'Related' }): $v") }
                }
                'IMPP' { $more.Add("IM: $v") }
                'X-SOCIALPROFILE' { $more.Add("Social: $v") }
                'PHOTO' { $cardExtras.Add(@('PHOTO', '', $v, 'Dropped', 'CSV cannot carry photos')) }
                default { if (-not $ignored.ContainsKey($n)) { $cardExtras.Add(@($n, $p.label, $v, 'Dropped', 'No mapping')) } }
            }
        }

        if ($fullName) { $row['Name'] = $fullName }
        else { $row['Name'] = (@([string]$row['First Name'], [string]$row['Middle Name'], [string]$row['Last Name']) -ne '') -join ' ' }
        if ($isCompany -and $row['Company']) {
            if ($row['First Name'] -eq $row['Company']) { $row['First Name'] = '' }
            if (-not $row['Name']) { $row['Name'] = $row['Company'] }
        } elseif (-not $row['First Name'] -and -not $row['Last Name'] -and $fullName) { $row['First Name'] = $fullName }

        # E-mail: preferred first, unique, three columns, the rest to Notes.
        $seen = @{}
        foreach ($pass in 0, 1) {
            foreach ($e in $emails) {
                if (($e.types -contains 'PREF') -ne ($pass -eq 0)) { continue }
                $address = $e.value.Trim()
                if (-not $address) { continue }
                $key = $address.ToLowerInvariant()
                if ($seen.ContainsKey($key)) { $cardExtras.Add(@('EMAIL', $e.label, $address, 'Dropped', 'Duplicate in card')); continue }
                $seen[$key] = 1
                $slot = $null
                foreach ($f in $emailSlots) { if (-not $row[$f]) { $slot = $f; break } }
                if ($slot) { $row[$slot] = $address }
                else { $more.Add("E-mail: $address"); $cardExtras.Add(@('EMAIL', $e.label, $address, 'Notes', 'No free e-mail column')) }
            }
        }

        # Phones: label-aware, preferred first, unique by digits, the rest to Notes.
        $seen = @{}
        foreach ($pass in 0, 1) {
            foreach ($pk in $phones) {
                $ph = $pk[0]
                $kinds = $pk[1]
                if (($ph.types -contains 'PREF') -ne ($pass -eq 0)) { continue }
                $number = $ph.value.Trim()
                if ($number.StartsWith('tel:', [StringComparison]::OrdinalIgnoreCase)) { $number = $number.Substring(4) }
                if (-not $number) { continue }
                $key = $number -replace '\D', ''
                if (-not $key) { $key = $number }
                if ($seen.ContainsKey($key)) { $cardExtras.Add(@('TEL', $ph.label, $number, 'Dropped', 'Duplicate in card')); continue }
                $seen[$key] = 1
                $fields =
                    if (($kinds -contains 'FAX') -and ($kinds -contains 'HOME')) { 'Home Fax', 'Other Fax' }
                    elseif (($kinds -contains 'FAX') -and ($kinds -contains 'OTHER')) { 'Other Fax', 'Business Fax' }
                    elseif ($kinds -contains 'FAX') { 'Business Fax', 'Other Fax' }
                    elseif ($kinds -contains 'PAGER') { 'Pager', 'Other Phone' }
                    elseif ($kinds -contains 'CELL') { 'Mobile Phone', 'Other Phone' }
                    elseif ($kinds -contains 'HOME') { 'Home Phone', 'Home Phone 2', 'Other Phone' }
                    elseif ($kinds -contains 'WORK') { 'Business Phone', 'Business Phone 2', 'Other Phone' }
                    elseif ($kinds -contains 'MAIN') { 'Company Main Phone', 'Primary Phone', 'Other Phone' }
                    elseif ($kinds -contains 'OTHER') { , 'Other Phone' }
                    else { 'Primary Phone', 'Other Phone' }
                $slot = $null
                foreach ($f in $fields) { if (-not $row[$f]) { $slot = $f; break } }
                if ($slot) { $row[$slot] = $number }
                else {
                    $label = $ph.label
                    if ($label.StartsWith('_$!<') -and $label.EndsWith('>!$_')) { $label = $label.Substring(4, $label.Length - 8) }
                    if (-not $label) { $label = (@($ph.types) -ne 'VOICE' -ne 'PREF') -join ' ' }
                    $more.Add("Phone$(if ($label) { " ($label)" }): $number")
                    $cardExtras.Add(@('TEL', $ph.label, $number, 'Notes', 'No free phone column'))
                }
            }
        }

        # Addresses: label-aware, the rest to Notes.
        foreach ($ak in $addresses) {
            $ad = $ak[0]
            $kinds = $ak[1]
            $parts = @($ad.parts)
            $d = @('', '', '', '', '', '', '')
            for ($m = 0; $m -lt 7 -and $m -lt $parts.Count; $m++) { $d[$m] = ([string]$parts[$m]).Trim() }
            $street = (@($d[2], $d[1], $d[0]) -ne '') -join $lf
            if (-not ($street + $d[3] + $d[4] + $d[5] + $d[6])) { continue }
            $want = if ($kinds -contains 'WORK') { 'Business' } elseif ($kinds -contains 'HOME') { 'Home' } else { 'Other' }
            $prefix = $null
            foreach ($f in $want, 'Other') { if (-not $row["$f Street"] -and -not $row["$f City"] -and -not $row["$f Postal Code"]) { $prefix = $f; break } }
            if ($prefix) {
                $row["$prefix Street"] = $street
                $row["$prefix City"] = $d[3]
                $row["$prefix State"] = $d[4]
                $row["$prefix Postal Code"] = $d[5]
                $row["$prefix Country/Region"] = $d[6]
            } else {
                $flat = ((@($street, $d[3], $d[4], $d[5], $d[6]) -ne '') -join ', ').Replace($lf, ', ')
                $more.Add("Address ($want): $flat")
                $cardExtras.Add(@('ADR', $ad.label, $flat, 'Notes', 'No free address block'))
            }
        }

        if ($urls.Count) {
            $row['Web Page'] = $urls[0]
            for ($m = 1; $m -lt $urls.Count; $m++) { $more.Add("Web: $($urls[$m])"); $cardExtras.Add(@('URL', '', $urls[$m], 'Notes', 'Only one web page column')) }
        }
        if ($more.Count) { $notes.Add(($more -join $lf)) }
        $row['Notes'] = $notes -join "$lf$lf"

        $displayName = if ($row['Name']) { $row['Name'] } else { [string]$row['Company'] }
        foreach ($x in $cardExtras) {
            $extras.Add([pscustomobject]@{ SourceIndex = $idx; Name = $displayName; Property = $x[0]; Label = $x[1]; Value = $x[2]; Action = $x[3]; Reason = $x[4] })
        }

        $identity = $false
        foreach ($key in $row.Keys) { if ($key -ne 'Notes' -and $row[$key]) { $identity = $true; break } }
        if (-not $identity) {
            $skipped.Add([pscustomobject]@{ SourceIndex = $idx; Properties = ((@($card.properties | ForEach-Object { $_.name }) | Select-Object -Unique) -join ',') })
            continue
        }

        # One CSV record with every field quoted, as ConvertTo-Csv writes it.
        [void]$csvLine.Clear()
        foreach ($h in $headers) {
            if ($csvLine.Length) { [void]$csvLine.Append(',') }
            $cell = $row[$h]
            if ($cell) { [void]$csvLine.Append('"').Append(([string]$cell).Replace('"', '""')).Append('"') } else { [void]$csvLine.Append('""') }
        }
        $record = $csvLine.ToString()
        $batchLines.Add($record)
        $mappedLines.Add('"' + $idx + '",' + $record)
        $sourceIndex.Add($idx)

        if ($row['Name'] -and $row['E-mail Address']) {
            $dk = ([string]$row['Name']).ToLowerInvariant() + '|' + ([string]$row['E-mail Address']).ToLowerInvariant()
            if ($duplicateKeys.ContainsKey($dk)) { $duplicateKeys[$dk].Add($idx) }
            else { $list = [System.Collections.Generic.List[int]]::new(); $list.Add($idx); $duplicateKeys[$dk] = $list }
        }
    }

    $header = (@($headers | ForEach-Object { '"' + $_ + '"' })) -join ','
    $mappedLines.Insert(0, '"SourceIndex",' + $header)
    [IO.File]::WriteAllLines((Join-Path $work '02-mapped.csv'), $mappedLines, $utf8Bom)
    $extras | Export-Csv -LiteralPath (Join-Path $work '02-extras.csv') -NoTypeInformation -Encoding UTF8
    $skipped | Export-Csv -LiteralPath (Join-Path $work '02-skipped.csv') -NoTypeInformation -Encoding UTF8
    $duplicates = @(foreach ($kv in $duplicateKeys.GetEnumerator()) {
            if ($kv.Value.Count -gt 1) { [pscustomobject]@{ NameAndEmail = $kv.Key; Count = $kv.Value.Count; SourceIndexes = ($kv.Value -join ',') } }
        })
    $duplicates | Export-Csv -LiteralPath (Join-Path $work '02-possible-duplicates.csv') -NoTypeInformation -Encoding UTF8
    Write-Verbose ("Stage 2: mapped {0} of {1} cards ({2:n1} s)" -f $batchLines.Count, $cards.Count, $watch.Elapsed.TotalSeconds)

    # --- Stage 3 ---------------------------------------------------------------------------------
    foreach ($f in $oldBatches) { Remove-Item -LiteralPath $f.FullName }
    $manifest = [System.Collections.Generic.List[object]]::new()
    $number = 0
    for ($o = 0; $o -lt $batchLines.Count; $o += $BatchSize) {
        $number++
        $take = [math]::Min($BatchSize, $batchLines.Count - $o)
        $file = 'OutlookContacts_{0:D3}.csv' -f $number
        $lines = [System.Collections.Generic.List[string]]::new($take + 1)
        $lines.Add($header)
        $lines.AddRange($batchLines.GetRange($o, $take))
        [IO.File]::WriteAllLines((Join-Path $OutputDirectory $file), $lines, $utf8Bom)
        $manifest.Add([pscustomobject]@{ File = $file; Contacts = $take; FirstSourceIndex = $sourceIndex[$o]; LastSourceIndex = $sourceIndex[$o + $take - 1] })
    }
    $manifest | Export-Csv -LiteralPath (Join-Path $OutputDirectory 'ImportManifest.csv') -NoTypeInformation -Encoding UTF8

    [pscustomobject]@{
        OutputDirectory = $OutputDirectory
        Cards = $cards.Count
        Exported = $batchLines.Count
        Skipped = $skipped.Count
        Extras = $extras.Count
        ExtrasByReason = @($extras | Group-Object Action, Reason | Sort-Object Count -Descending | ForEach-Object { [pscustomobject]@{ Count = $_.Count; Reason = $_.Name } })
        PossibleDuplicates = $duplicates.Count
        Batches = $manifest.ToArray()
        Seconds = [math]::Round($watch.Elapsed.TotalSeconds, 1)
    }
}