比较一个数组中的字符串,另一个数组中使用通配符字符串

Scr*_*key 2 arrays powershell compare wildcard

我有两个数组,$a并且$b,在数组中$a是一个字符串,可以部分匹配其中一个条目$b,假设我可以使用通配符:

$a = "1", "Computer Name", "2"
$b = "3", "4", "Full Computer Name Here"

foreach ($line in $a) {
    foreach ($line2 in $b) {
         where "*$line*" -like "*$line2*"
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里想一切简单的后拿到"这个数组,数组匹配",进入foreach了一个数组,然后尝试了所有的Select-StringCompare-Object $line $line2 -ExcludeDifferent -IncludeEqual -PassThru,但不能得到任何工作.

理想情况下,它会返回"匹配的完整计算机名称".

Sid*_*Sid 7

你试过这个吗?

$a = "1","Computer Name","2"
$b = "3","4","Full Computer Name Here"
foreach ($line in $a ) {
    $b -match $line
}
Run Code Online (Sandbox Code Playgroud)

编辑: 尽管@Ansgar在评论中说明了它的简单性,但可能不是最好的答案.有时PowerShell是如此不一致,这让我想知道为什么我仍然使用它.

  • 感谢您提醒我,比较运算符也隐含地用作枚举器.但请注意,`-match`运算符执行正则表达式匹配,如果比较字符串包含特殊字符,则可能会产生不需要的结果. (3认同)
  • `$ a ="foo."; $ b ="foo.example.org","foobar.example.org"` (3认同)

Ans*_*ers 6

Where-Object不这样做.它从您的代码中没有的管道中读取.此外,您的比较是向后的,您不能将通配符添加到参考值.

将您的代码更改为以下内容:

foreach ($line in $a) {
    $b | Where-Object { $_ -like "*${line}*" }
}
Run Code Online (Sandbox Code Playgroud)

或者像这样:

foreach ($line in $a) {
    foreach ($line2 in $b) {
        if ($line2 -like "*${line}*") { $line2 }
    }
}
Run Code Online (Sandbox Code Playgroud)

它会做你期望的.

编辑:

我一直忘记比较运算符也可以作为枚举器,因此后一个例子可以简化为类似的东西(删除嵌套循环和条件):

foreach ($line in $a) {
    $b -like "*${line}*"
}
Run Code Online (Sandbox Code Playgroud)