假设我有以下场景:一个IP地址链接到一个特定的字符串,我想匹配一个操作。
示例:
需要使用什么来拥有"漂亮"的代码,而不是多个if循环?IP address: 1.1.1.1 String: "Home" IP address: 5.5.5.5 String: "Work"
这里最简单的方法是创建一个查找哈希表,其中IP是键,对应的字符串是值:
$lookupIP = @{
'1.1.1.1' = 'Home'
'5.5.5.5' = 'Work'
# etcetera
}
现在,如果你在一个变量中有一个ip,只需执行
$ip = '1.1.1.1'
# Do something with the corresponding string
Write-Host "$ip will do something with $($lookupIP[$ip])"
如果你愿意,你可以先添加一个测试,看看$ip是否可以在查找表中找到:
if ($lookupIP.ContainsKey($ip)) {
Write-Host "$ip will do something with $($lookupIP[$ip])"
}
else {
Write-Warning "IP '$ip' was not found in the hashtable.."
}