Saturday, 15 August 2015

powershell compare 2 arrays output if match -



powershell compare 2 arrays output if match -

i have 2 arrays want compare items of

i have array [hi,no,lo,yes,because] , array b [mick,tickle,fickle,pickle,ni,hi,no,lo,yes,because]

so want search every item in , compare every item in b , if there match homecoming "there match"

one-liner:

foreach ($elem in $a) { if ($b -contains $elem) { "there match" } }

but may more convenient count matches:

$c = 0; foreach ($elem in $a) { if ($b -contains $elem) { $c++ } } "{0} matches found" -f $c

or if want check if arrays intersect @ all:

foreach ($elem in $a) { if ($b -contains $elem) { "there match"; break } }

or if want check if $a subset of $b:

$c = 0; foreach ($elem in $a) { if ($b -contains $elem) { $c++ } } if ($c -eq $a.count) { '$a subset of $b' }

finally there's compare-object cmdlet improve of above. illustration (outputs elements nowadays in both arrays):

compare-object -includeequal -excludedifferent $a $b

powershell

No comments:

Post a Comment