Kahn Kah
Kahn Kah

Reputation: 1453

Usage of hashtable in PowerShell to replace objects

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 ?

Upvotes: 0

Views: 53

Answers (1)

Theo
Theo

Reputation: 61068

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.."
}

Upvotes: 1

Related Questions