【发布时间】:2017-04-13 07:49:17
【问题描述】:
我正在使用 cmdlet ConvertFrom-Json 从 JSON 文件中收集数据。到目前为止有效。 JSON 包含一个哈希表数组。
[
{
"userSamAccountName": "jodoe",
"QuotaGroup": "AD-Group-Contoso-1"
},
{
"userSamAccountName": "jodoe",
"QuotaGroup": "AD-Group-Contoso-2"
},
{
"userSamAccountName": "frmark",
"QuotaGroup": "AD-Group-Contoso-1"
},
{
"userSamAccountName": "frmark",
"QuotaGroup": "AD-Group-Contoso-2"
}
]
现在我有另一个包含一些重叠数据的哈希表数组。
[
{
"userSamAccountName": "jodoe",
"QuotaGroup": "AD-Group-Contoso-1"
},
{
"userSamAccountName": "jodoe",
"QuotaGroup": "AD-Group-Contoso-2"
},
{
"userSamAccountName": "niwellenstein",
"QuotaGroup": "AD-Group-Contoso-1"
},
{
"userSamAccountName": "niwellenstein",
"QuotaGroup": "AD-Group-Contoso-2"
}
]
我想将它们组合起来而不重复。
我尝试了一些 cmdlety,例如 select -Unique 和 .Contains(),但它并没有像我希望的那样工作。
背景:我有一系列广告组。在此组中,用户只能成为一个组的成员 - 例如:jodoe 可以是 AD-Group-Contoso-1 或 AD-Group-Contoso-2 的成员,但不能同时成为这两个组的成员。我需要报告他们。 报告文件将由向管理员报告的计划任务处理。第一个脚本每 20 分钟运行一次,从第一个脚本处理报告文件的报告计划任务每天运行一次 - 所以我不想在我的报告文件中有重复。
这是我到目前为止尝试过的代码:
# Group users in list to check if user is in 2 or more Groups #
$reportDuplicates = $adUserlist |
group -Property userSamAccountName |
? { $_.Count -gt 1 }
# only select the group of the duplicates #
# $reportDuplicates.Group corresponds to the Json File #
$reportDuplicates = $reportDuplicates.Group
$reportPath = "C:\\temp\\reports\\"
$reportDuplicatesPath = $reportPath + "reportADDuplicates.json"
# Check if file already exists #
if (Test-Path $reportDuplicatesPath) {
# load existing reports #
$existingDuplicatesReport = Get-Content $reportDuplicatesPath |
ConvertFrom-Json
$reportDuplicates.ForEach({
if ($existingDuplicatesReport.Contains($_)) {
$existingDuplicatesReport.Add($_)
}
})
# convert to JSON and save in file #
$existingDuplicatesReport | ConvertTo-Json | Out-File $reportDuplicatesPath
} else {
# convert to JSON and save in file #
$reportDuplicates | ConvertTo-Json | Out-File $reportDuplicatesPath
}
但它不起作用,我有感觉,我无法检查哈希表数组是否包含哈希表?
如果我将它们全部推入数组并执行select -Unique,我只会得到哈希表数组的第一个条目。
【问题讨论】:
-
哈希表是引用类型,
Contains()将寻找具有完全相同身份的对象,而不是具有相似内容的对象。您必须遍历集合并手动进行比较
标签: arrays json powershell hashtable contains