如何在 Powershell 中对多维数组使用 where 子句进行 foreach 循环?

Pa3*_*k.m 3 powershell

例如

$people = @(
 @('adam', '24', 'M')
 @('andy', '20', 'M')
 @('alex', '30', 'M')
 @('ava', '25', 'F')
)

foreach($person in $people | where ($person[1] -lt '25') -and ($person[2] -eq 'M'))
Run Code Online (Sandbox Code Playgroud)

这应该选择adamandy...

San*_*zon 5

您的语句应该使用的语法Where-Object是:

$people = @(
    @('adam', '24', 'M'),
    @('andy', '20', 'M'),
    @('alex', '30', 'M'),
    @('ava', '25', 'F')
)

$people | Where-Object { $_[1] -lt '25' -and $_[2] -eq 'M' } | ForEach-Object { $_[0] }

# Results in:
#
# adam
# andy
Run Code Online (Sandbox Code Playgroud)

或者使用foreach带有if语句的传统循环:

foreach($array in $people) {
    if($array[1] -lt 25 -and $array[2] -eq 'M') {
        $array[0]
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,正如前面的答案中所建议的,哈希表可能更适合于此(即使语法有点复杂):

$people = @{
    M = @{
        24 = 'adam'
        20 = 'andy'
        30 = 'alex'
    }
    F = @{
        25 = 'ava'
    }
}

$people['M'][$people['M'].Keys -lt 25]
Run Code Online (Sandbox Code Playgroud)