如果匹配,powershell 比较 2 个数组输出

use*_*513 3 powershell

我有两个数组,我想比较它们的项目

我有数组 A [hi,no,lo,yes,because] 和数组 B [mick,tickle,fickle,pickle,ni,hi,no,lo,yes,because]

所以我想搜索 A 中的每个项目并与 B 中的每个项目进行比较,如果有匹配返回“有匹配”

Ale*_*sht 8

单线:

foreach ($elem in $A) { if ($B -contains $elem) { "there is a match" } }
Run Code Online (Sandbox Code Playgroud)

但计算匹配可能更方便:

$c = 0; foreach ($elem in $A) { if ($B -contains $elem) { $c++ } }
"{0} matches found" -f $c
Run Code Online (Sandbox Code Playgroud)

或者,如果您想检查数组是否相交:

foreach ($elem in $A) { if ($B -contains $elem) { "there is a match"; break } }
Run Code Online (Sandbox Code Playgroud)

或者,如果您想检查 $A 是否是 $B 的子集:

$c = 0; foreach ($elem in $A) { if ($B -contains $elem) { $c++ } }
if ($c -eq $A.Count) { '$A is a subset of $B' }
Run Code Online (Sandbox Code Playgroud)

最后是 Compare-Object cmdlet,它实际上比以上所有命令都要好。示例(仅输出两个数组中都存在的元素):

Compare-Object -IncludeEqual -ExcludeDifferent $A $B
Run Code Online (Sandbox Code Playgroud)