如何在PowerShell中遍历JSON匹配门店类型并执行对应函数?
问题场景
我有如下test.json文件:
[ { "STORE":"2001", "UUID":"d7985d5f", "Clock1":"91", "Type":"IP" }, { "STORE":"2002", "UUID":"821a0368", "Clock1":"92", "Type":"GT" } ]
同时已有如下处理逗号分隔字符串的PowerShell代码:
$StoreInput = "2001,2002" $StoreArray = $StoreInput.Split(",") $storemap = Get-Content "location\test.json" | ConvertFrom-Json
需要实现的功能:读取$StoreArray中的门店编号,匹配$storemap中对应门店的Type字段,根据类型执行对应函数并传入该门店的UUID和Clock1参数:
if (type = IP) { Function1 -Clock $Clock1 (from the json) -UUID $UUID (from the json) #对应2001的数据 }elseif (type = GT) { Function2 -Clock $Clock1 (from the json) -UUID $UUID (from the json) #对应2002的数据 }
实现方案
直接遍历门店列表,匹配对应JSON记录后按类型执行函数即可,完整代码如下:
# 定义示例函数(实际使用时替换为你的真实业务函数) function Function1 { param( [string]$Clock, [string]$UUID ) Write-Host "执行Function1: Clock=$Clock, UUID=$UUID" } function Function2 { param( [string]$Clock, [string]$UUID ) Write-Host "执行Function2: Clock=$Clock, UUID=$UUID" } # 现有门店处理代码 $StoreInput = "2001,2002" $StoreArray = $StoreInput.Split(",") # 读取并解析JSON文件(补充原代码缺失的Get-Content) $storemap = Get-Content "location\test.json" | ConvertFrom-Json # 核心逻辑:遍历门店,匹配记录并执行对应函数 foreach ($store in $StoreArray) { # 定位当前门店的JSON记录 $storeRecord = $storemap | Where-Object { $_.STORE -eq $store } if (-not $storeRecord) { Write-Warning "未找到门店$store的记录" continue } # 根据Type分支执行函数 switch ($storeRecord.Type) { "IP" { Function1 -Clock $storeRecord.Clock1 -UUID $storeRecord.UUID } "GT" { Function2 -Clock $storeRecord.Clock1 -UUID $storeRecord.UUID } default { Write-Warning "门店$store的类型$($storeRecord.Type)无对应处理函数" } } }
关键说明
- 原代码读取JSON时缺少
Get-Content,必须添加才能正确读取文件内容并转换为JSON对象 - 用
foreach遍历门店列表,通过Where-Object精准匹配对应门店的记录 - 使用
switch语句替代if/elseif,后续新增类型时扩展更便捷 - 增加异常处理:找不到门店记录或类型不匹配时,会输出警告提示
内容的提问来源于stack exchange,提问作者Laba Ningombam
相关产品推荐
相关产品推荐

