Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading