Powershell中CSV数据与JSON配置对象的匹配查询实现问题
问题解决方法
问题根源
你之前用CSV作为配置时,导入后直接得到一维配置数组,可直接调用.Where()方法筛选。但改用当前JSON结构后,ConvertFrom-Json返回的是顶层自定义对象,配置项分散在Messagequeue1、Messagequeue2两个属性对应的数组中,直接对顶层对象调用.Where()自然无法生效。
解决步骤
- 先将所有分散的配置数组合并为一个一维数组,即可沿用之前的筛选逻辑
- 注意属性名匹配和匹配规则的选择:JSON中配置字段为
dfs、errormsg,Powershell不区分属性名大小写,但如果需要精确匹配字段值,建议用-eq替代-Match(-Match为正则匹配,遇到特殊字符易出现非预期结果)
修正后完整代码
$json = "C:\Temp\Example.json" $MessageQueue = Get-Content -Path $json | ConvertFrom-Json # 新增:合并所有配置项为一维数组 $allConfig = $MessageQueue.PSObject.Properties.Value | ForEach-Object { $_ } $Param = @{ Header = 'DFS','MessageQueue','ErrorMessage','CreatedDate','StartTime' Path = 'C:\temp\file.csv' } $SqlFile = Import-Csv @Param | Select-Object -Skip 2 | Select-Object -SkipLast 2 $teamemails = @{} $itsemails = @() ForEach ($sqlerror In $SqlFile){ # 筛选源改为合并后的$allConfig,需要精确匹配可把-Match替换为-eq if ($Config = $allConfig.Where({ $_.dfs -Match $sqlerror.DFS -And $_.errormsg -Match $sqlerror.ErrorMessage -And $_.Messagequeue -Match $sqlerror.MessageQueue})) { Write-Host "Match sending to " -NoNewline Write-Output -InputObject $Config.Team foreach ($c in $config) { if ($teamemails[$c.Team] -eq $null) { $teamemails[$c.Team] = @() } $teamemails[$c.Team] += $sqlerror } } else { Write-host 'No Match sending to default' $itsemails += $sqlerror } }
可选优化
如果后续会新增更多MessagequeueX配置分组,不需要修改合并逻辑,代码会自动读取所有顶层属性下的配置项。
内容的提问来源于stack exchange,提问作者Ben Donachie
相关产品推荐
相关产品推荐

