skydesportensdag/scripts/update-postal-codes.ps1

33 lines
1.8 KiB
PowerShell

$ErrorActionPreference = 'Stop'
$archivePath = Join-Path ([System.IO.Path]::GetTempPath()) ('dk-postcodes-' + [guid]::NewGuid() + '.zip')
try {
Invoke-WebRequest 'https://download.geonames.org/export/zip/DK.zip' -OutFile $archivePath
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archive = [System.IO.Compression.ZipFile]::OpenRead($archivePath)
try {
$reader = [System.IO.StreamReader]::new($archive.GetEntry('DK.txt').Open())
try { $data = $reader.ReadToEnd() } finally { $reader.Dispose() }
} finally { $archive.Dispose() }
$cities = [ordered]@{}
$locations = [ordered]@{}
foreach ($row in $data.Trim().Split("`n")) {
$fields = $row.TrimEnd("`r").Split("`t")
if ($fields[0] -ne 'DK' -or $fields[1] -notmatch '^\d{4}$' -or !$fields[2]) {
throw 'Ugyldig postnummerdata.'
}
if ($cities.Contains($fields[1]) -and $cities[$fields[1]] -ne $fields[2]) {
throw "Flere postbyer for postnummer $($fields[1])."
}
$cities[$fields[1]] = $fields[2]
$locations[$fields[1]] = @{ city = $fields[2]; lat = [double]::Parse($fields[9], [Globalization.CultureInfo]::InvariantCulture); lng = [double]::Parse($fields[10], [Globalization.CultureInfo]::InvariantCulture) }
}
if ($cities.Count -lt 1000) { throw 'Postnummerlisten er ufuldstændig.' }
$target = Join-Path $PSScriptRoot '../wwwroot/postnumre.json'
$cities | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $target -Encoding utf8
$locations | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath (Join-Path $PSScriptRoot '../wwwroot/postnummer-positioner.json') -Encoding utf8
Write-Output "Gemt $($cities.Count) danske postnumre."
} finally {
if (Test-Path -LiteralPath $archivePath) { Remove-Item -LiteralPath $archivePath }
}