0

Let's say I have the following scenario: An IP address is linked to a particular string and I want to match an action.

Example:

IP address: 1.1.1.1

String: "Home"

IP address: 5.5.5.5

String: "Work"
if($IP -eq 1.1.1.1) 

{  
   #Do something with "Home"
}

What would I be needing to use to have 'pretty' code instead of multiple if loops ?

1 Answer 1

1

The easiest thing to do here is to create a lookup Hashtable where IP's are the keys, and the corresponding strings are the values:

$lookupIP = @{
    '1.1.1.1' = 'Home'
    '5.5.5.5' = 'Work'
    # etcetera
}

Now, if you have an ip in a variable, simply do

$ip = '1.1.1.1'
# Do something with the corresponding string
Write-Host "$ip will do something with $($lookupIP[$ip])"

If you like, you can add a test first to see if the $ip can be found in the lookup table:

if ($lookupIP.ContainsKey($ip)) {
    Write-Host "$ip will do something with $($lookupIP[$ip])"
}
else {
    Write-Warning "IP '$ip' was not found in the hashtable.."
}
Sign up to request clarification or add additional context in comments.

1 Comment

@KahnKah $lookupIP[$ip] will print Home if the value of $ip was '1.1.1.1', and it prints Work when the value of $ip was '5.5.5.5'

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.