Powershell: if elements of array1 contain elements in array2, what am I doing wrong here?

I'm 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 on behaving like "crashing" when I run this piece of code

He gives me "Bingo" when ONLY 1 item is in$zvmtozvmconnection

Those. I delete "ZVM0004" and only "ZVM003" remains, I get "Bingo"

I also tested -match

and it didn't work

Please, help

+3


source to share


3 answers


-contains

does not work. It checks if one element is contained in the array. -in

matches another order ( $array -contains $item

or $item -in $array

).

To do this, you need to use the cmdlet Compare-Object

:



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

      

+3


source


another method



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

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

      

+2


source


As one liner:

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

      

And with all the errors in the allocated 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"}

      

0


source







All Articles