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 find and get value from multi dimensional array in powershell?

Basically I have an array that looks something like

areaCodes = @ (
 @("310", "LA"),
 @("212", "NY"),
 @("702", "LV")
)

I would like to have it so that for example if I have a variable $code = $212 Find if it is in the list, and if is, get the value associated with it.

Something like

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

if($areaCodes.contains($code))
{
 WRITE-HOST $areaCodes[1]
}

and this would output NY

How do I do this in powershell? Or is there are more efficient way to do this?

>Solution :

You need to enumerate all arrays inside your array for this to work, for example:

($areaCodes | Where-Object { $_ -contains $code })[1] # => NY

Or using an actual loop:

foreach($array in $areaCodes) {
    if($array -contains $code) {
        $array[1]
        break
    }
}

But taking a step back, a hash table seems a lot more appropriate for your use case:

$code = 212
$areaCodes = @{
    310 = "LA"
    212 = "NY"
    702 = "LV"
}

$areaCodes[$code] # => NY
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