MicrosoftDocs / PowerShell-Docs

The official PowerShell documentation sources
https://learn.microsoft.com/powershell
Other
1.97k stars 1.56k forks source link

Default sort properties are insufficiently described #6382

Closed yecril71pl closed 4 years ago

yecril71pl commented 4 years ago

Documentation Issue

The help page for Sort-Object should document that default properties come from Types.ps1xml and that if none are provided or defined, the objects themselves will be compared.

Context of the issue

Conceptual content

Cmdlet reference & about_ topics

Detailed description of the issue

When I sort objects of type [DRAWING.SIZE] by default properties, the result is as if after comparing the strings corresponding to those objects—meaning that 12 comes before 2. There is no support for this phenomenon in the current documentation because it does not say what happens when neither explicit nor default properties are available.

sdwheeler commented 4 years ago

Yes. I saw your PR for this as well. There is a lot to detail here that I am researching.

yecril71pl commented 4 years ago

About default parameters

SortObjectCommand performs its duty under EndProcessing.
It calls OrderByProperty to decide how to sort. It calls ProcessExpressionParameter to find out whether any parameters are specified or deducible. The default parameters are deduced by GetDefaultKeyPropertySet, which is called on the first object. GetDefaultKeyPropertySet reads the object’s PSStandardMembers.DefaultKeyPropertySet, the rest of this story is documented.

Still no properties?

OrderByProperty calls CreateOrderMatrix, which calls OrderByPropertyEntryEvaluationHelper.ProcessObject for each object. ProcessObject, in the interesting case of no properties specified, which is typical for primitive objects, returns ObjectCommandPropertyValue. ObjectCommandPropertyValue checks if the object is IComparable, otherwise it calls ToString (which is slow and gives an unexpected result with numbers).

Takeaway

Sorting objects that are not comparable, including objects of value types, without specifying the sorting key explicitly should be avoided. However, it is difficult to specify the sorting key when such an object is a property of another object, so it is best to provide your own default sorting key for the object’s type. In order to get there, you need to call Update-TypeData, which modifies the global environment, so you must be careful. HTH

sdwheeler commented 4 years ago

Thanks for the research. This is what I was seeing as well. Much of this is more detail than is needed in the Sort-Object article. But it would be good information for a deep dive article.

I will update your PR. Let me know what you think of the changes.