【问题标题】:Check if array of hashtables contains a hashtable检查哈希表数组是否包含哈希表
【发布时间】: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


【解决方案1】:

告诉Select-Object您要在嵌套哈希表的哪些键上建立唯一性:

$arr1 = $json1 | ConvertFrom-Json
$arr2 = $json2 | ConvertFrom-Json

$arr1 + $arr2 | Select-Object -Unique 'userSamAccountName', 'QuotaGroup'

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2019-08-08
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多