Powershell中比较CSV和JSON对象



我希望使用JSON构建一个基本的配置文件。首先,我查询一个SQL数据库以获得3个值。这3个值存储在CSV中,我想遍历我的JSON配置文件,寻找匹配项。如果匹配,我想将标头和所有密钥对传递给Powershell变量。

我已经设法使用CSV作为配置文件来实现这一点,但JSON似乎不支持";。其中";我完全被卡住了。

这是我的JSON文件。我比较SQL文件的3个值是DFS、消息队列和错误。如果他们匹配,我想最终通过电子邮件向团队分配3个值。

{
"Messagequeue1": [
{
"dfs": "OAKHILL",
"Messagequeue": "IMPORTSEQ",
"errormsg": "Input in non-input field",
"Ignore" : "false",
"team": "ben@team.com.au",
"teamcc": "middle-office@team.com.au",
"escalate": "60"
}
]
,"Messagequeue2": [
{
"dfs": "MQ",
"Messagequeue": "MX",
"errormsg": "ERRORMESS",
"Ignore" : "false",
"team": "middle-office@team.com.au",
"teamcc": "",
"escalate": "60"
}           
]
} 

Powershell在下面。

$json = "C:TempExample.json"
$MessageQueue = Get-Content -Path $json | ConvertFrom-Json 
$Param = @{
Header = 'DFS','MessageQueue','ErrorMessage','CreatedDate','StartTime'
Path = 'C:tempfile.csv'
}
$SqlFile = Import-Csv @Param | Select-Object -Skip 2 | Select-Object -SkipLast 2 
$teamemails = @{}
$itsemails = @()
$MessageQueue | gm -MemberType Methods
ForEach ($sqlerror In $SqlFile){

if ($Config = $MessageQueue.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)
{
$c.Resend

if ($teamemails[$c.Team] -eq $null) {
$teamemails[$c.Team] = @()
}
$teamemails[$c.Team] += $sqlerror
}
}

else {
Write-host  'No Match sending to default'
$itsemails += $sqlerror
}
}

$MessageQueue包含具有两个属性MessageQueue1MessageQueue2的单个自定义对象-.Where({})仅对集合进行有意义的操作

您可以更改条件以测试@($MessageQueue.MessageQueue1, $MessageQueue.MessageQueue2).Where({...}),但如果json文件包含更多属性,这显然会中断。

您可以使用隐藏的psobject成员集来枚举如下属性:

# create a flat array from the individual property values
$MessageQueue = $MessageQueue.psobject.Properties |ForEach-Object Value

或者使用Get-Member来发现属性名称:

# same as above, create a flat array from the individual property values
$MessageQueue = ($MessageQueue |Get-Member -MemberType Property) |ForEach-Object { $MessageQueue.$_ }

最新更新