2

I have two variables in sorted order.

$a contains

Gi1/1
Gi1/2

$b contains

Gi1/1
Gi1/2
Gi1/3

I tried to compare two variables whether it is equal or not equal as below:

if($a -eq $b) {
    write-host "equal"
} else {
    write-host "not equal"
}

but it didn't seem to work. The output should be "not equal", but it outputs as "equal". How can I fix this?

4
  • 2
    How are your $a and $b variables being declared? You haven't provided enough information. Commented Mar 12, 2018 at 14:20
  • I agree with @TheIncorrigible1 - you need to update your question so it shows how the two variables are being assigned. (Are you really sure they are String objects, for example?) Commented Mar 12, 2018 at 15:18
  • 1
    In the comment to the one answer, he says they're created using Select-String @Bill_Stewart Commented Mar 12, 2018 at 15:20
  • Understand - but the question is still incomplete IMO. Commented Mar 12, 2018 at 15:21

1 Answer 1

4

What you have are two arrays (being returned from Select-String), but you're trying to do a string comparison. When you do that, it's trying to do:

$a.ToString() == $b.ToString()

which is

"System.Object[]" == "System.Object[]"

A workaround, if the array only contains strings, is to concatenate them equally and then compare:

$a = @('Gi1/1', 'Gi1/2')
$b = @('Gi1/1', 'Gi1/2', 'Gi1/3')

if (($a -join '') -eq ($b -join '')) {
    'Equal'
}
else {
    'Not equal'
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.