在PowerShell中比较多个数组值的更优雅的方法

时间:2014-04-29 21:31:45

标签: powershell

在PowerShell中编写以下if语句是否有更优雅的方法

[ValidateNotNull()]
[ValidateSet('Service', 'Role', 'RoleService', 'Feature', 'Group', 'File', 'Package')]
[Parameter(Mandatory = $true, Position = 1)]
[string[]]
$ProcessingModes

if ($ProcessingModes -contains 'Role' -or $ProcessingModes -contains 'RoleService' -or $ProcessingModes -contains 'Feature')
{
}

3 个答案:

答案 0 :(得分:3)

你可以很容易地做到阵列交叉:

$keyModes = 'Role', 'RoleService', 'Feature'
if ($keyModes | ? { $ProcessingModes -contains $_ }) { "found at least one" }

答案 1 :(得分:1)

您的问题基本上是,PowerShell中是否有运算符确定两个数组之间的交集是否为非空。答案是否定的,没有。此外,在查看问题Powershell, kind of set intersection built-in?之后,看起来最好的方法是使用HashSet个对象而不是数组,它们会公开IntersectWithUnionWith方法。

答案 2 :(得分:0)

您可以改用RegEx。这是我的处理方式:

$ProcessingModes = @('Role','Service')
if ($ProcessingModes -match '\b(Role|RoleService|Feature)\b') {
    'it matches'
} else {
    'it does not match'
}
it matches

$ProcessingModes = @('RoleGroup','Service')
if ($ProcessingModes -match '\b(Role|RoleService|Feature)\b') {
    'it matches'
} else {
    'it does not match'
}
it does not match

\b是一个单词边界。相当于搜索“整个单词”。由于您的ValidateSet,它在代码中不是绝对必要的,但是如果您允许的话,它将有助于避免在“ RoleGroup”之类的其他单词中找到“ Role”。您可以尝试在第二个示例中删除两个\b来查看它们是否匹配。

我认为这将使您的代码更具可读性,并且可能更优雅。

相关问题