AdilZ
AdilZ

Reputation: 1197

Powershell: if items in array1 contain items in array2, what am I doing wrong here

I am not sure what I am doing wrong here:

    $ZertoGenericAlert =  "VRA0030"
    $ZvmToVraConnection = "ZVM0002"
    $ZvmToZvmConnection = "ZVM0003", "ZVM0004"

  $thoseerrors = "ZVM0002", "VPG0006", "VPG0004" , "ZVM0003", "ZVM0004"

  if ($thoseerrors -contains $ZvmToZvmConnection) {Echo "bingo"} Else {Echo "fail"}

It keeps coming as "fail" when I run that that entire piece of code

It gives me "Bingo" when ONLY 1 item is found in the $zvmtozvmconnection

Ie I remove "ZVM0004" and only "ZVM003" remains i get "Bingo"

I also tested -match and that did not work either

Please help

Upvotes: 3

Views: 1071

Answers (3)

k7s5a
k7s5a

Reputation: 1377

As a one liner:

if($thoseerrors | ? {$ZvmToZvmConnection -contains $_}) {Echo "bingo"} Else {Echo "fail"}

And with all errors in a separated array.

# Existing errors stored in $errors
$errors = $thoseerrors | Where {$ZvmToZvmConnection -contains $_}

# Check if the $errors array contains elements
if($errors){Echo "bingo"} Else {Echo "fail"}

Upvotes: 0

Esperento57
Esperento57

Reputation: 17492

other method

$resul=$ZvmToZvmConnection | where {$_ -in $thoseerrors} | select -First 1

if ($resul) 
{
    'bingo'
} 
else 
{
    'fail'
}

Upvotes: 3

briantist
briantist

Reputation: 47872

-contains doesn't work that way. It checks if a single item is contained in an array. -in is the same, with the other order ($array -contains $item or $item -in $array).

You should use the Compare-Object cmdlet for this:

if ((Compare-Object -ReferenceObject $thoseerrors -DifferenceObject $ZvmToZvmConnection -ExcludeDifferent -IncludeEqual)) {
    'bingo'
} else {
    'fail'
}

Upvotes: 3

Related Questions