MicrosoftDocs / PowerShell-Docs

The official PowerShell documentation sources
https://learn.microsoft.com/powershell
Creative Commons Attribution 4.0 International
1.93k stars 1.55k forks source link

Document -eq operator when right and left operators are lists #11163

Closed i5513 closed 1 month ago

i5513 commented 1 month ago

Type of issue

Missing information

Feedback

At this about page we can see that this return false: "abc" -eq "abc", "def"

But, is there any expresion where:

xxx -eq "abc","def"

is true ?

I tested:

$a="abc", "def"
$a -eq $a # empty return (expected)
,$a -eq $a # works
abc
def
$a,$a -eq $a # works
abc
def
abc
def
,$a,$a,$a -eq $a # not clear for me why this behaviour
abc
def
abc
def
,$a -eq "abc","def" # empty return (why is it not like previous example?)
,$a -eq @("abc","def") # empty return (why is it not like previous example?)
,@("abc","def") -eq @("abc","def") # empty return

Thank you for clarifing what is happening there!

Page URL

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.4

Content source URL

https://github.com/MicrosoftDocs/PowerShell-Docs/blob/main/reference/7.4/Microsoft.PowerShell.Core/About/about_Comparison_Operators.md

Author

@sdwheeler

Document Id

742e7d8c-b6bc-6939-3e9d-b25bcc14dfed

sdwheeler commented 1 month ago

Short answer is that we don't really support comparing two collections using the comparison operators.

Long answer: the right-hand operand is treated as a singleton. That singleton object (array in your example) is compared to each item in the collection on the left-hand side. Since the singleton object is an array, the comparison becomes a reference comparison. It will only match when the right-hand object refers to the same instance of the left-hand object. Since you are comparing $a to $a, the -eq operator will find matching references.

When you compare $a -eq "abc","def", those are two different instances, so the references don't match.

If you want to compare all the values in one array with the values in another array you have to enumerate the items yourself and compare.