Powershell Left Join 后的条件属性

问题描述 投票:0回答:1

当我通过 Powershell 对两个对象进行左连接时,我定义了一个属性“名称”。如果记录存在,我希望该属性在右侧对象中具有“名称”字段的值,如果不存在,则在左侧对象中具有“名称”字段的值。

我尝试过各种条件语句,例如

@{ Name = If($Right.Length -eq 0){'Left.Name'}else{'Right.Name'}}
@{ Name = If($Right -eq $null){'Left.Name'}else{'Right.Name'}}
@{ Name = If($null -eq $Right){'Left.Name'}else{'Right.Name'}}

但是我尝试过的每个条件语句要么总是评估为真,要么总是评估为假。

显然,我错过了一些东西。我该怎么做?

开始编辑:

$objectA = @(
@{
"Id"="1"
"Name"="Bob"
}, 
@{
"Id"="2"
"Name"="Bill"
},
@{
"Id"="3"
"Name"="Ted"
}
) 


$objectB = @(
@{
"Id"="2"
"Name"="John"
}
) 

$objectA | leftjoin $objectB -On Id -Property @{ID = 'Left.ID'}, @{Name = If($Right -ne $null){'Left.Name'}else{'Right.Name'}}|Format-Table

我希望输出看起来像:

ID Name
-- ----
1  Bob    
2  John
3  Ted
powershell conditional-statements properties
1个回答
0
投票

不清楚

leftjoin
是什么,但假设它的工作原理与
Select-Object
的计算属性类似,这就可以解决问题:

$objectA = @(
    @{
        'Id'   = '1'
        'Name' = 'Bob'
    },
    @{
        'Id'   = '2'
        'Name' = 'Bill'
    },
    @{
        'Id'   = '3'
        'Name' = 'Ted'
    }
)


$objectB = @(
    @{
        'Id'   = '2'
        'Name' = 'John'
    }
)

# assuming `$objectB` is an array of mutliple objects
# you will want a hashtable here for fast lookups,
# `Group-Object -AsHashtable` is an easy and efficient way to create one
$objectBMap = $objectB | Group-Object Id -AsHashTable -AsString
$objectA | Select-Object @(
    'Id'
    @{ 
        Name       = 'Name'
        Expression = {
            # if the Id from exists in the right
            if ($objectBMap.ContainsKey($_.Id)) {
                # use the Name from the right
                return $objectBMap[$_.Id].Name
            }
            # else, use the Name from the left
            $_.Name
        }
    })
© www.soinside.com 2019 - 2024. All rights reserved.