Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell multi-dimensional collection logic for -eq

Thanks to PowerShell Logic, I'm familiar with some intricacies of how -eq works when the left operand is a collection - rather than a boolean, -eq will return an array of elements that equal the right operand. From the 3.0 spec:

If the value designated by the left operand is not a collection, the result has type bool. Otherwise, the result is a possibly empty unconstrained 1-dimensional array containing the elements of the collection that test True when compared to the value designated by the right operand.

That said, I've found a case that doesn't quite make sense to me. If I declare an array with an element that is also an array, I can't actually get -eq to match that element:

$a = @( 1, @(2, 3) )
$a -eq 1              # results in an array with a single element, containing 1
$a -eq @( 2, 3 )      # results in an empty array

What's going on? It's not particularly easy to tell if this is PowerShell wrapping mixed-type array elements, wrapping two dimensional arrays, issues with value vs. reference type equality checks, or any subset of those.

like image 639
Ian Pugsley Avatar asked May 25 '26 09:05

Ian Pugsley


1 Answers

I believe it has to with that fact that array comparison in .NET only compares that the two objects refer to the same object, not that they have equivalent values. Consider:

# ~> @(2,3).Equals(@(2,3))
False

# ~> $arr = @(2,3)

# ~> $arr.Equals($arr)
True

# ~> $arr.Equals(@(2,3))
False

# ~> @(1, $arr) -eq $arr
2
3
like image 92
zdan Avatar answered May 27 '26 00:05

zdan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!