-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
Note:
-
The problem occurs if the the array elements are invisibly
[psobject]-wrapped, as happens when you create an array via aWrite-Outputcall, for instance. -
As such, it is another manifestation of Objects are situationally invisibly [psobject]-wrapped, sometimes causing unexpected behavior. #5579.
Array.Sort() is just one manifestation: any .NET method call with an array / object[]-typed array argument that relies on seeing the true array element types rather than their incidental [psobject] wrappers will behave unexpectedly from the user's perspective.
Steps to reproduce
# OK, with array constructed *by an expression*.
$a = "b", "ä", "a"; [Array]::Sort($a, [StringComparer]::Ordinal)
$a -join ' ' | Should -Be "a b ä" # OK - non-ASCII character ä comes LAST in ordinal sorting.
# !! BROKEN, with array constructed via Write-Output, resulting in
# !! individually [psobject]-wrapped strings.
$a = Write-Output "b", "ä", "a"; [Array]::Sort($a, [StringComparer]::Ordinal)
$a -join ' ' | Should -Be "a b ä" # !! BROKEN - outputs "a ä b" insteadExpected behavior
Both tests should succeed, as it shouldn't matter how the array is constructed.
Actual behavior
The 2nd test fails:
Expected strings to be the same, but they were different. String lengths are both 5. Strings differ at index 2.
Expected: 'a b ä' But was: 'a ä b'
That is, the string-comparer argument was effectively ignored, because the .Sort() method saw psobject instances, not strings.
Environment data
PowerShell Core 7.2.0-preview.3