You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Name Value
---------
PSVersion 7.3.0
PSEdition Core
GitCommitId 7.3.0
OS Darwin 21.6.0 Darwin Kernel Version 21.6.0: Wed Aug 1014:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6…
Platform Unix
PSCompatibleVersions {1.0,2.0,3.0,4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
In English A À Å all sort together even though US 7-bit ASCII doesn't include accented characters and Unicode must maintain compatibility so the A+Accent isn't near A
In Norwegian Å is treated as a distinct letter. so in English
l> "a", "b" , "y", "å", "z", "Z,", "Å", "Y", "B", "A" | sort-object
a
A
å
Å
b
B
y
Y
z
Z,
The accented characters sort on their own, with the unaccented character. But change the culture...
PS> "a", "b" , "y", "å", "z", "Z,", "Å", "Y", "B", "A" | sort-object -Culture no-no
a
A
b
B
y
Y
z
Z,
å
Å
The culture basically dictates if we sort upper before lowercase or lower before upper case, and I think most are upper-last / lower-first
Greater than and less than then work on where the character would be sorted , not on its unicode value (because if you we used 8 bit encodings, some characters like € might not have a value or might have different values depending on the active code page. ASCII, being for American in the 1950s doesn't have €)
a sorts before A so is "less than" even though [int]"a" is greater than [int]"A" .
for string operands, -cgt eventually comes down to the .NET method Cultureinfo.CompareInfo.Compare("A", "a", CompareOptions.None), and the cultureInfo used in PoweShell is InvariantCulture. The return value is 1 in this case, and that's why "A" -cgt "a" returns true.
The .NET equivalent of ASCII values - which are limited to the legacy 7-bit ASCII "alphabet" (limited to 128 characters) - are Unicode code points, because .NET [string]s are Unicode strings, composed of [char] instances, which are UTF-16 code units, i.e. in effect [uint16] values, which therefore have a range of 0x0 - 65535 (0xFFFF); Unicode's code points are a superset of ASCII values, however.
Note that, despite their name, [char] instances are only typically, but not always whole characters, namely only for those code points in the so-called BMP (Basic Multilingual Plane); for characters outside that plane, i.e. those with a code point above65535 (0xFFFF), which notably includes emojj, they form either half of a surrogate pair; that is, two[char] instances are needed to represent a character outside the BMP.
In practice, when strings are compared in a manner that requires ordering (less-than, equal, or greater-than), a linguistic (human-language-based), culture-specific collation order is often used (though the .NET APIs don't use that term) - and such an order is unrelated to (Unicode) code points.
Usually, corresponding lowercase and uppercase letters are grouped together, with lowercase letters coming before their uppercase counterparts, and with accented variants often, but not necessarily, being grouped with their base characters, as James O'Neill (@jhoneill)'s examples show (add -CaseSensitive for predictable results).
In .NET, these culture-specific rules are implemented via per-culture implementations of the System.Globalization.CompareInfo class.
By contrast, comparing strings purely numerically by their characters' code points is called an ordinal comparison.
PowerShell compares [string] instances using a culture-specific collation order, i.e. it does not perform ordinal comparison.
For two given strings, use [string]::Compare() with an ordinal System.StringComparison value, e.g.:
[string]::Compare('a', 'A', [StringComparison]::Ordinal) ... 32, i.e., the difference in code-point values; that the number is positive implies that a is greater than A, in an ordinal sense.
[string]::Compare('a', 'A', [StringComparison]::OrdinalIgnoreCase) ... 0, because - after culture-invariant transformation of both input strings to uppercase - their code points are identical.
For sorting, Sort-Object does not offer a solution, because the only way to fundamentally modify the sort order is with a -Culture argument, and there isn't a culture that that performs ordinal comparisons.
$a = 'a', 'A'; [Array]::Sort($a, [StringComparer]::Ordinal); $a # -> 'A', 'a', i.e. ordinal sorting took place.
By contrast, [char] instances always use (ultimately) ordinal comparison; note that PowerShell always requires a [char] cast, even with single-character string literals such as 'a', given that PowerShell has no built-in literal syntax for [char] (unlike C#, where '.<some-char>' is exclusively a char literal):
For (non-)equality comparison (-eq, -ne), case is respected, if requested:
[char] 'a' -ceq [char] 'A' -> $false, because the characters' code points aren't identical.
[char] 'a' -eq [char] 'A' -> $true, because - after culture-invariant transformation to uppercase, the two characters' code points are identical.
[char] 'a' -ieq [char] 'A' -> ditto, -ieq is effectively an alias of -eq
For less-than(-or-equal) / greater-than (-or-equal) comparisons, case is ignored, because ordinal comparison is invariably performed:
[char] 'a' -cgt [char] 'A' -> $true, because the code point of char. a (LATIN SMALL LETTER A, U+0061) is greater than the code point of A (LATIN CAPITAL LETTER A, U+0041)
[char] 'a' -gt [char] 'A'-> !! ditto (also with -igt); that is, requests to ignore case are not honored.
The above is plain wrong, either it is greater than or it is equal to. Both can't be true. (quantum joke are left as an exercise for the reader)
I don't know if char comparisons should always be case insensitive but different behaviour between eq and ge/gt/le/lt must be wrong. If culture is addressed (with a "legacy behaviour" option) this should be addressed at the same time. Some subtle bugs could be created where code unwittingly relies on those on current behaviour, so any change probably should be opt in.
(I've also updated the previous comment, which indeed took me a while to write, but I wanted to have a systematic overview, including for my own notes; I may reuse parts in future Stack Overflow answers)
Note that PowerShell predominantly uses the invariant culture (operators, casts, string interpolation), and, from that vantage point, it is cmdlets that use the current culture (by default) that amount to an inconsistency.
I think Select-String is another example.
Unless there is a good reason for this bifurcation that I am missing.
Activity
jhoneill commentedon Nov 22, 2022
It is more complicated than the ASCII values.
Consider A À Å ; a à and å
In English A À Å all sort together even though US 7-bit ASCII doesn't include accented characters and Unicode must maintain compatibility so the A+Accent isn't near A
In Norwegian Å is treated as a distinct letter. so in English
The accented characters sort on their own, with the unaccented character. But change the culture...
The culture basically dictates if we sort upper before lowercase or lower before upper case, and I think most are upper-last / lower-first
Greater than and less than then work on where the character would be sorted , not on its unicode value (because if you we used 8 bit encodings, some characters like € might not have a value or might have different values depending on the active code page. ASCII, being for American in the 1950s doesn't have €)
a sorts before A so is "less than" even though [int]"a" is greater than [int]"A" .
b sorts after "À" (but before "B") so
.
daxian-dbw commentedon Nov 23, 2022
A
TL;DRanswer that supplement James O'Neill (@jhoneill)'s answer above is:-cgteventually comes down to the .NET methodCultureinfo.CompareInfo.Compare("A", "a", CompareOptions.None), and thecultureInfoused in PoweShell isInvariantCulture. The return value is 1 in this case, and that's why"A" -cgt "a"returns true.mklement0 commentedon Nov 24, 2022
Let me try a comprehensive summary:
Terminology:
The .NET equivalent of ASCII values - which are limited to the legacy 7-bit ASCII "alphabet" (limited to 128 characters) - are Unicode code points, because .NET
[string]s are Unicode strings, composed of[char]instances, which are UTF-16 code units, i.e. in effect[uint16]values, which therefore have a range of0x0-65535(0xFFFF); Unicode's code points are a superset of ASCII values, however.[char]instances are only typically, but not always whole characters, namely only for those code points in the so-called BMP (Basic Multilingual Plane); for characters outside that plane, i.e. those with a code point above65535(0xFFFF), which notably includes emojj, they form either half of a surrogate pair; that is, two[char]instances are needed to represent a character outside the BMP.In practice, when strings are compared in a manner that requires ordering (less-than, equal, or greater-than), a linguistic (human-language-based), culture-specific collation order is often used (though the .NET APIs don't use that term) - and such an order is unrelated to (Unicode) code points.
Usually, corresponding lowercase and uppercase letters are grouped together, with lowercase letters coming before their uppercase counterparts, and with accented variants often, but not necessarily, being grouped with their base characters, as James O'Neill (@jhoneill)'s examples show (add
-CaseSensitivefor predictable results).In .NET, these culture-specific rules are implemented via per-culture implementations of the
System.Globalization.CompareInfoclass.By contrast, comparing strings purely numerically by their characters' code points is called an ordinal comparison.
PowerShell compares
[string]instances using a culture-specific collation order, i.e. it does not perform ordinal comparison.As Dongbo Wang (@daxian-dbw) points out, PowerShell's operators use the invariant culture,
[cultureinfo]::InvariantCultureBy contrast,
Sort-Objectuses the current culture ([cultureinfo]::CurrentCulture, as also returned byGet-Culture).This discrepancy is unfortunate, and can make a difference, as James O'Neill (@jhoneill)'s examples show (add
-CaseSensitivefor predictable results). Unfortunately, as of v7.3.0, requesting the invariant culture via-Culture ([cultureinfo]::InvariantCulture)does not work: see Sort-Object, unlike operators, uses the current culture and doesn't support requesting the invariant culture via -Culture #18655If you want ordinal comparison:
[string]::Compare()with an ordinalSystem.StringComparisonvalue, e.g.:[string]::Compare('a', 'A', [StringComparison]::Ordinal)...32, i.e., the difference in code-point values; that the number is positive implies thatais greater thanA, in an ordinal sense.[string]::Compare('a', 'A', [StringComparison]::OrdinalIgnoreCase)...0, because - after culture-invariant transformation of both input strings to uppercase - their code points are identical.Sort-Objectdoes not offer a solution, because the only way to fundamentally modify the sort order is with a-Cultureargument, and there isn't a culture that that performs ordinal comparisons.System.Arraytype has a staticSort()method with an overload that accepts aSystem.Collections.IComparerinstance, to which you can pass aSystem.StringComparerinstance - note that this method sorts in place:$a = 'a', 'A'; [Array]::Sort($a, [StringComparer]::Ordinal); $a# -> 'A', 'a', i.e. ordinal sorting took place.By contrast,
[char]instances always use (ultimately) ordinal comparison; note that PowerShell always requires a[char]cast, even with single-character string literals such as'a', given that PowerShell has no built-in literal syntax for[char](unlike C#, where'.<some-char>'is exclusively acharliteral):-eq,-ne), case is respected, if requested:[char] 'a' -ceq [char] 'A'-> $false, because the characters' code points aren't identical.[char] 'a' -eq [char] 'A'-> $true, because - after culture-invariant transformation to uppercase, the two characters' code points are identical.[char] 'a' -ieq [char] 'A'-> ditto,-ieqis effectively an alias of-eqCompare-Objectcompares[char]instances case-sensitively by default: see Compare-Object with [char] instances is unexpectedly case-sensitive by default #17758[char] 'a' -cgt [char] 'A'-> $true, because the code point of char.a(LATIN SMALL LETTER A,U+0061) is greater than the code point ofA(LATIN CAPITAL LETTER A,U+0041)[char] 'a' -gt [char] 'A'-> !! ditto (also with-igt); that is, requests to ignore case are not honored.jhoneill commentedon Nov 24, 2022
Michael Klement (@mklement0) (a hat tip to your thoroughness, although you must be neglecting other things in life :-) this looks like a bug to me
The above is plain wrong, either it is greater than or it is equal to. Both can't be true. (quantum joke are left as an exercise for the reader)
I don't know if
charcomparisons should always be case insensitive but different behaviour betweeneqandge/gt/le/ltmust be wrong. If culture is addressed (with a "legacy behaviour" option) this should be addressed at the same time. Some subtle bugs could be created where code unwittingly relies on those on current behaviour, so any change probably should be opt in.Do we know if this has been flagged before ?
mklement0 commentedon Nov 24, 2022
Thanks, James O'Neill (@jhoneill); I agree that it is a bug, and I've created #18659
(I've also updated the previous comment, which indeed took me a while to write, but I wanted to have a systematic overview, including for my own notes; I may reuse parts in future Stack Overflow answers)
Note that PowerShell predominantly uses the invariant culture (operators, casts, string interpolation), and, from that vantage point, it is cmdlets that use the current culture (by default) that amount to an inconsistency.
I think
Select-Stringis another example.Unless there is a good reason for this bifurcation that I am missing.