Public/ConvertFrom-NSPVCard.ps1
|
function ConvertFrom-NSPVCard { <# .SYNOPSIS Parses a multi-contact vCard file (Apple Contacts export, vCard 2.1/3.0/4.0) into one record per card, or into a JSON Lines file. .DESCRIPTION Unfolds continuation lines, joins quoted-printable soft breaks, splits group, name, TYPE values and other parameters, and decodes vCard escapes (\\ \n \, \; \:). Structured values (N, ADR, ORG) are also split into Parts. Apple item labels (item1.X-ABLabel) are attached to the property of the same group as Label. PHOTO data is replaced by its length. Without -OutFile, one object per card is emitted: Index, Properties (Name, Group, Types, Label, Parameters, Value, Parts) With -OutFile, each card is written as one JSON line with the same fields in camelCase (index, properties, name, group, types, label, parameters, value, parts) and a summary object is returned. That file is what Export-NSPOutlookContactCsv reuses. Performance note: Windows PowerShell 5.1 pays a high price per PowerShell function call and per New-Object, so the per-line path uses inline .NET calls only. .EXAMPLE ConvertFrom-NSPVCard -Path .\Contacts.vcf | Select-Object -First 1 -ExpandProperty Properties .EXAMPLE ConvertFrom-NSPVCard -Path .\Contacts.vcf -OutFile .\contacts.jsonl #> [CmdletBinding()] param( [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Path, [string]$OutFile ) $resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath Add-Type -AssemblyName System.Web $enc = [System.Web.HttpUtility] $nul = [string][char]0 $lf = "`n" $structured = @{ 'N' = 1; 'ADR' = 1; 'ORG' = 1 } $escapedSep = [regex]::new('(?<!\\);') $escapedAny = [regex]::new('(?s)\\(.)') $watch = [Diagnostics.Stopwatch]::StartNew() function ConvertFrom-QuotedPrintable([string]$Value) { # Legacy vCard 2.1 only, so a function call is acceptable here. $bytes = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i -lt $Value.Length; $i++) { if ($Value[$i] -eq '=' -and $i + 2 -lt $Value.Length -and $Value.Substring($i + 1, 2) -match '^[0-9A-Fa-f]{2}$') { $bytes.Add([Convert]::ToByte($Value.Substring($i + 1, 2), 16)); $i += 2 } else { $bytes.AddRange([Text.Encoding]::UTF8.GetBytes([string]$Value[$i])) } } [Text.Encoding]::UTF8.GetString($bytes.ToArray()) } $writer = $null if ($OutFile) { $outDir = Split-Path -Parent ([IO.Path]::GetFullPath($OutFile)) if ($outDir -and -not (Test-Path -LiteralPath $outDir)) { $null = New-Item -ItemType Directory -Force -Path $outDir } $writer = [System.IO.StreamWriter]::new([IO.Path]::GetFullPath($OutFile), $false, [System.Text.UTF8Encoding]::new($false)) } $reader = [System.IO.StreamReader]::new($resolved, [Text.Encoding]::UTF8, $true) $cards = 0 $inside = $false $props = [System.Collections.Generic.List[object]]::new() $labels = @{} $types = [System.Collections.Generic.List[string]]::new() $sb = [System.Text.StringBuilder]::new() $out = [System.Text.StringBuilder]::new() $have = $false $qp = $false try { while ($true) { $raw = $reader.ReadLine() if ($null -ne $raw) { # Folding: a leading space or tab continues the previous logical line. if ($have -and $raw.Length -gt 0 -and ($raw[0] -eq ' ' -or $raw[0] -eq "`t")) { [void]$sb.Append($raw, 1, $raw.Length - 1); continue } # Quoted-printable soft line break. if ($have -and $qp -and $sb.Length -gt 0 -and $sb[$sb.Length - 1] -eq '=') { $sb.Length--; [void]$sb.Append($raw); continue } } if ($have) { $line = $sb.ToString() $colon = $line.IndexOf(':') $quote = $line.IndexOf('"') if ($quote -ge 0 -and $quote -lt $colon) { $inQuote = $false; $colon = -1 for ($k = 0; $k -lt $line.Length; $k++) { $c = $line[$k]; if ($c -eq '"') { $inQuote = -not $inQuote } elseif ($c -eq ':' -and -not $inQuote) { $colon = $k; break } } } if ($colon -gt 0) { $left = $line.Substring(0, $colon) $value = $line.Substring($colon + 1) $segs = $left.Split(';') $dot = $segs[0].IndexOf('.') $group = if ($dot -ge 0) { $segs[0].Substring(0, $dot) } else { '' } $name = $segs[0].Substring($dot + 1).ToUpperInvariant() if ($name -eq 'BEGIN' -and $value -ieq 'VCARD') { $inside = $true; $props.Clear(); $labels.Clear() } elseif ($name -eq 'END' -and $value -ieq 'VCARD' -and $inside) { $cards++ $inside = $false if ($writer) { [void]$out.Clear() [void]$out.Append('{"index":').Append($cards).Append(',"properties":[') for ($k = 0; $k -lt $props.Count; $k++) { $p = $props[$k] $label = if ($p[1] -and $labels.ContainsKey($p[1])) { $labels[$p[1]] } else { '' } if ($k) { [void]$out.Append(',') } [void]$out.Append('{"name":').Append($enc::JavaScriptStringEncode($p[0], $true)) [void]$out.Append(',"group":').Append($enc::JavaScriptStringEncode($p[1], $true)).Append(',"types":[') $t = $p[2] for ($m = 0; $m -lt $t.Length; $m++) { if ($m) { [void]$out.Append(',') }; [void]$out.Append($enc::JavaScriptStringEncode($t[$m], $true)) } [void]$out.Append('],"label":') if ($label) { [void]$out.Append($enc::JavaScriptStringEncode($label, $true)) } else { [void]$out.Append('""') } [void]$out.Append(',"parameters":') if ($p[3]) { [void]$out.Append($enc::JavaScriptStringEncode($p[3], $true)) } else { [void]$out.Append('""') } [void]$out.Append(',"value":').Append($enc::JavaScriptStringEncode($p[4], $true)) if ($null -ne $p[5]) { [void]$out.Append(',"parts":[') $parts = $p[5] for ($m = 0; $m -lt $parts.Length; $m++) { if ($m) { [void]$out.Append(',') }; [void]$out.Append($enc::JavaScriptStringEncode($parts[$m], $true)) } [void]$out.Append(']') } [void]$out.Append('}') } [void]$out.Append(']}') $writer.WriteLine($out.ToString()) } else { $items = foreach ($p in $props) { [pscustomobject]@{ Name = $p[0] Group = $p[1] Types = $p[2] Label = $(if ($p[1] -and $labels.ContainsKey($p[1])) { $labels[$p[1]] } else { '' }) Parameters = $p[3] Value = $p[4] Parts = $p[5] } } [pscustomobject]@{ Index = $cards; Properties = @($items) } } } elseif ($inside) { if ($name -eq 'X-ABLABEL') { if ($group) { $labels[$group] = $value } } else { $types.Clear() $extra = '' for ($k = 1; $k -lt $segs.Length; $k++) { $s = $segs[$k] $eq = $s.IndexOf('=') if ($eq -lt 0) { $types.Add($s.Trim().ToUpperInvariant()) } elseif ($s.Substring(0, $eq) -ieq 'TYPE') { foreach ($t in $s.Substring($eq + 1).Replace('"', '').Split(',')) { $types.Add($t.Trim().ToUpperInvariant()) } } elseif ($extra) { $extra += ";$s" } else { $extra = $s } } if ($extra -and $extra.IndexOf('QUOTED-PRINTABLE', [StringComparison]::OrdinalIgnoreCase) -ge 0) { $value = ConvertFrom-QuotedPrintable $value } $parts = $null if ($name -eq 'PHOTO') { $decoded = "[photo $($value.Length) chars]" } elseif ($value.IndexOf('\') -lt 0) { $decoded = $value if ($structured.ContainsKey($name)) { $parts = $value.Split(';') } } else { # \\ is held as NUL while \n, \N and other \x escapes are resolved. $held = $value.Replace('\\', $nul) $decoded = $escapedAny.Replace($held.Replace('\n', $lf).Replace('\N', $lf), '$1').Replace($nul, '\') if ($structured.ContainsKey($name)) { $parts = $escapedSep.Split($held) for ($m = 0; $m -lt $parts.Length; $m++) { $parts[$m] = $escapedAny.Replace($parts[$m].Replace('\n', $lf).Replace('\N', $lf), '$1').Replace($nul, '\') } } } $props.Add(@($name, $group, $types.ToArray(), $extra, $decoded, $parts)) } } } } if ($null -eq $raw) { break } [void]$sb.Clear() [void]$sb.Append($raw) $have = $true $c0 = $raw.IndexOf(':') $qp = $c0 -gt 0 -and $raw.Substring(0, $c0).IndexOf('QUOTED-PRINTABLE', [StringComparison]::OrdinalIgnoreCase) -ge 0 } } finally { $reader.Dispose() if ($writer) { $writer.Dispose() } } if ($inside) { Write-Warning 'The vCard file ends inside an unfinished card; that card was not returned.' } Write-Verbose ("Parsed {0} cards in {1:n1} s" -f $cards, $watch.Elapsed.TotalSeconds) if ($writer) { [pscustomobject]@{ Path = $resolved; OutFile = [IO.Path]::GetFullPath($OutFile); Cards = $cards; Seconds = [math]::Round($watch.Elapsed.TotalSeconds, 1) } } } |