Home > OS >  How do I find and get value from multi dimensional array in powershell?
How do I find and get value from multi dimensional array in powershell?

Time:05-18

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

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?

CodePudding user response:

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
  • Related