我需要根据哈希表中的值在 PowerShell 中做出一些决定。
基本上我需要根据属性(公司属性)在 Active Directory 中分配用户的 UPN,并想创建一个包含这样的键和值的哈希表
Key Value Company1 @Company1.com Company2 @Company2.com
The issue I am facing is I don't know how to tell PowerShell to use a value rather than another based on the company attribute, basically I don't know how to cycle/check the company attribute against the key in the hashtable.
I've tried to use switches like
$a -match $hashTable
或
$a -contains $hashtable
收效甚微。
我认为哈希表是我在这里需要的,但我当然愿意接受任何建议,例如使用外部文件进行匹配,因为我需要匹配的公司数量相当多。
最佳答案
同时 Mathias已经提出了适当的解决方案,我想添加更多解释。
Hashtables和 switch
语句本质上是对同一问题的两种不同解决方案:将输入值转换为相应的输出。
A → "foo" B → "bar" C → "baz" ...
Hashtables are the simpler (and faster) approach, where you look up the result to the input value in a pre-defined table. Their advantage is that you can implement the associations in one place (e.g. a declaration section of your code where you define all your (static) data) and use them in a very simple manner anywhere else in your code:
$domains = @{
'Company1' = '@Company1.com'
'Company2' = '@Company2.com'
}
$name = 'foo'
$company = 'Company1'
$addr = $name + $domains[$company]
switch
语句的处理更复杂,但也更通用。例如,除了简单的查找之外,它们还允许进行不同类型的比较(通配符、正则表达式)。如果未列出值,它们还允许提供默认值/操作。对于哈希表,您需要使用附加的 if
/else
语句来处理这些情况,如 Mathias 所示,除非您对哈希表在查找不返回时返回的空值感到满意。找不到匹配项。
$name = 'foo'
$company = 'Company1'
$domain = switch ($company) {
'Company1' { '@Company1.com' }
'Company2' { '@Company2.com' }
default { throw 'Unknown company' }
}
$addr = $name + $domain
关于powershell - 在 PowerShell 中将 Hashtable 与 switch case 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43409993/