1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the hash table! I did not know these existed. It is exactly what I am looking for!
@Pa3k.m my pleasure :) a hashtable is what you may know as a dictionary in other languages (such as Python for example)
Another question - Would it be possible to put arrays inside a hash table?
How do I do it? Because everytime I put an array as a Hash Table value, it ends up being combined into 1
Nevermind, it looks like I was just having problems with datatypes
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.