powershell - Powershell选择唯一字段

标签 powershell unique select-object

我有一些字段的对象列表。例如,列表中有三个对象:

Field1 = "aaa"
Field2 = 123
Field3 = "ccc"

Field1 = "bbb"
Field2 = 123
Field3 = "ddd"

Field1 = "eee"
Field2 = 123
Field3 = "ccc"

我需要像这样过滤此列表:
  • 我必须对Field2-Field3进行所有唯一的匹配。字段1的值是不必要的。

  • 在我的示例中,选择的结果必须删除第三个对象,因为在Field2和Field3上具有相同的值。

    我已经尝试过Select-Object -Unique Field2, Field3,但没有过滤任何内容。

    我也尝试过Where-Object,但结果相同。

    任何的想法?我使用的是Powershell的旧版本,因此无法使用某些cmdlet。

    谢谢。

    这是代码:它可以工作,但是我还需要在输出中获取Field1
    $result = @{}
     foreach($item in $myList) {
           $combined = '{0}-{1}' -f $item.Field2, $item.Field3
           if($result.ContainsKey($combined) -eq $false) {
              $result[$combined] = $item
           }
        }
        $result.Values
    

    最佳答案

    您可以使用一个表达式:

    $objects | Select -Unique @{n='Combined'; e={'{0}-{1}' -f $_.Field2, $_.Field3}}
    

    这是使用哈希的另一种方式:
    $result = @{}
    foreach($item in $objects){
        $combined = '{0}-{1}' -f $item.Field2, $item.Field3
        if($result.ContainsKey($combined) -eq $false){
            $result[$combined] = $item
        }
    }
    $result.Values | Select Field1
    

    关于powershell - Powershell选择唯一字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694093/

    相关文章:

    powershell - 如何在计算机启动时运行 PowerShell 脚本?

    powershell - 您能否在发布管理中将一个 PowerShell 任务的输出通过管道传输到另一个任务?

    dataframe - Julia DataFrames 唯一行

    powershell - 使用 Select-Object 在非默认属性之间指定

    powershell - Select-Object cmdlet 中要输出的可变数量的字段

    powershell - 如何在 PowerShell 数组中反转横向

    Powershell 选择字符串 : Get results by named regex group

    MySQL:对行组合设置唯一限制的问题

    python - 从嵌套列表和元组列表中获取所有唯一字符串

    有关排序和管道的 PowerShell 问题