将一个数组中的字符串与另一个数组中的通配符字符串进行比较
Compare a string in one array, with a wildcard string in another
我有两个数组,$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*"
}
}
我在尝试了所有简单的 'this array matches that array' 后来到这里,进入 foreach
一个数组,然后尝试了所有 Select-String
到 Compare-Object $line $line2 -ExcludeDifferent -IncludeEqual -PassThru
,但是不能'什么都做不了。
理想情况下,它会 return 'Full Computer Name Here' 它匹配的地方。
Where-Object
这样不行。它从您的代码中没有的管道中读取。还有,你的比较是倒退的,参考值一定不能加通配符。
将您的代码更改为如下内容:
foreach ($line in $a) {
$b | Where-Object { $_ -like "*${line}*" }
}
或者像这样:
foreach ($line in $a) {
foreach ($line2 in $b) {
if ($line2 -like "*${line}*") { $line2 }
}
}
它会如您所愿。
编辑:
我一直忘记比较运算符也可以用作枚举器,因此后一个示例可以简化为如下所示(删除嵌套循环和条件):
foreach ($line in $a) {
$b -like "*${line}*"
}
你试过吗?
$a = "1","Computer Name","2"
$b = "3","4","Full Computer Name Here"
foreach ($line in $a ) {
$b -match $line
}
编辑:
可能不是最好的答案,尽管它很简单,正如@Ansgar 在评论中所说明的那样。有时 PowerShell 是如此不一致,这让我想知道为什么我仍然使用它。
$b | Where {$_ | Select-String $a}
2018-06-23 更新
感谢 LotsPings 的评论,以进一步将其最小化为:
显然,Select-String
本身已经有两个迭代器,因此可以简化为:
$b | Select-String $a
PS C:\> $a = "1", "Computer Name", "Other Name"
PS C:\> $b = "Computer", "4", "Full Computer Name Here", "something else", "Also full computer name here"
PS C:\> $b | Select-String $a
Full Computer Name Here
Also full computer name here
我有两个数组,$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*"
}
}
我在尝试了所有简单的 'this array matches that array' 后来到这里,进入 foreach
一个数组,然后尝试了所有 Select-String
到 Compare-Object $line $line2 -ExcludeDifferent -IncludeEqual -PassThru
,但是不能'什么都做不了。
理想情况下,它会 return 'Full Computer Name Here' 它匹配的地方。
Where-Object
这样不行。它从您的代码中没有的管道中读取。还有,你的比较是倒退的,参考值一定不能加通配符。
将您的代码更改为如下内容:
foreach ($line in $a) {
$b | Where-Object { $_ -like "*${line}*" }
}
或者像这样:
foreach ($line in $a) {
foreach ($line2 in $b) {
if ($line2 -like "*${line}*") { $line2 }
}
}
它会如您所愿。
编辑:
我一直忘记比较运算符也可以用作枚举器,因此后一个示例可以简化为如下所示(删除嵌套循环和条件):
foreach ($line in $a) {
$b -like "*${line}*"
}
你试过吗?
$a = "1","Computer Name","2"
$b = "3","4","Full Computer Name Here"
foreach ($line in $a ) {
$b -match $line
}
编辑: 可能不是最好的答案,尽管它很简单,正如@Ansgar 在评论中所说明的那样。有时 PowerShell 是如此不一致,这让我想知道为什么我仍然使用它。
$b | Where {$_ | Select-String $a}
2018-06-23 更新
感谢 LotsPings 的评论,以进一步将其最小化为:
显然,Select-String
本身已经有两个迭代器,因此可以简化为:
$b | Select-String $a
PS C:\> $a = "1", "Computer Name", "Other Name"
PS C:\> $b = "Computer", "4", "Full Computer Name Here", "something else", "Also full computer name here"
PS C:\> $b | Select-String $a
Full Computer Name Here
Also full computer name here