- $ErrorActionPreference = "Stop"
- $Api = "https://dmfw.mca.gov.cn/9095/xzqh/getList"
- $OutFile = "D:\xzqh.csv"
- # Beijing, Tianjin, Shanghai, Chongqing
- $MunicipalCodes = @("110000", "120000", "310000", "500000")
- function Get-Code6 {
- param($Code)
- if ($null -eq $Code) {
- return ""
- }
- $s = [string]$Code
- if ($s -match "^\d{6}") {
- return $matches[0]
- }
- return $s
- }
- function Get-Children {
- param($Node)
- if ($null -eq $Node) {
- return @()
- }
- $names = $Node.PSObject.Properties.Name
- foreach ($p in @("children", "childList", "list")) {
- if ($names -contains $p) {
- if ($null -ne $Node.$p) {
- return @($Node.$p)
- }
- }
- }
- return @()
- }
- function Get-RootList {
- param($Json)
- if ($null -ne $Json.response.data.children) {
- return @($Json.response.data.children)
- }
- if ($null -ne $Json.data.children) {
- return @($Json.data.children)
- }
- if ($null -ne $Json.children) {
- return @($Json.children)
- }
- if ($null -ne $Json.data) {
- return @($Json.data)
- }
- throw "Can not find root list."
- }
- function Invoke-Xzqh {
- param(
- [string]$Code = "",
- [int]$MaxLevel = 3
- )
- $encCode = [uri]::EscapeDataString($Code)
- $url = $Api + "?code=" + $encCode + "&maxLevel=" + $MaxLevel
- Invoke-RestMethod `
- -Method Get `
- -Uri $url `
- -Headers @{
- "User-Agent" = "Mozilla/5.0"
- "Accept" = "application/json"
- } `
- -TimeoutSec 90
- }
- $Rows = New-Object System.Collections.Generic.List[object]
- function Add-Row {
- param(
- [string]$L1,
- [string]$L2,
- [string]$L3,
- $Code
- )
- $code6 = Get-Code6 $Code
- $Rows.Add([pscustomobject]@{
- L1 = $L1
- L2 = $L2
- L3 = $L3
- "行政区划代码" = $code6
- })
- }
- Write-Host "Downloading..."
- $json = Invoke-Xzqh -Code "" -MaxLevel 3
- $provinces = Get-RootList $json
- foreach ($p in $provinces) {
- $pName = [string]$p.name
- $pCode6 = Get-Code6 $p.code
- if ([string]::IsNullOrWhiteSpace($pName)) {
- continue
- }
- Add-Row $pName "" "" $p.code
- $pChildren = Get-Children $p
- if ($MunicipalCodes -contains $pCode6) {
- foreach ($d in $pChildren) {
- $dName = [string]$d.name
- if ([string]::IsNullOrWhiteSpace($dName)) {
- continue
- }
- Add-Row $pName $dName "" $d.code
- }
- continue
- }
- foreach ($c in $pChildren) {
- $cName = [string]$c.name
- if ([string]::IsNullOrWhiteSpace($cName)) {
- continue
- }
- Add-Row $pName $cName "" $c.code
- $districts = Get-Children $c
- foreach ($d in $districts) {
- $dName = [string]$d.name
- if ([string]::IsNullOrWhiteSpace($dName)) {
- continue
- }
- Add-Row $pName $cName $dName $d.code
- }
- }
- }
- $csv = $Rows | ConvertTo-Csv -NoTypeInformation
- $utf8Bom = New-Object System.Text.UTF8Encoding $true
- [System.IO.File]::WriteAllLines($OutFile, $csv, $utf8Bom)
- Write-Host ("Done: " + $OutFile)
- Write-Host ("Rows: " + $Rows.Count)
复制代码
被AI秒了...第一次报错,回复说是编码搞坏了,第2次就是这个代码 |