Home > Enterprise >  How do I do foreach loop with a where clause for a multidimensional array in Powershell?
How do I do foreach loop with a where clause for a multidimensional array in Powershell?

Time:05-19

For example

$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'))

and this should select adam and andy...

CodePudding user response:

The syntax you should use for your Where-Object statement would be:

$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

Or using a traditional foreach loop with an if statement:

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

However as recommended in previous answer, a hash table might be more suitable for this (even though the syntax is a bit more complicated):

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

$people['M'][$people['M'].Keys -lt 25]

CodePudding user response:

You can use the answer involving ForEach-Object of course. The only possible issue with this (depending on what you are trying to do with that data) is that a ForEach-Object will execute each record of data individually.

Another way is to create the object you want specifically then use a standard foreach().

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

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

foreach($person in $$filteredPeople) {

#stuff

}

This will do the same functionality on the whole object.

  • Related