rGA145
rGA145

Reputation: 204

How do I sort an array of objects by one of their property values in Powershell?

For example, I have a variable, which returns the line with several arrays:

@{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10}

I want to sort this line alphabetically by one of parameters. In this case - by sourceDSAcn, so result must be like that:

@{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10}

How can I do that?

Upvotes: 8

Views: 15310

Answers (1)

mklement0
mklement0

Reputation: 437478

Your output format suggests two things:

  • The objects aren't arrays, but custom objects ([pscustomobject] instances).

  • You've used the Write-Host cmdet to print these objects to the host (display), which results in the hashtable-literal-like representation shown in your question (see this answer).

    • If, instead, you want the usual rich display formatting you get by default - while still sending the output to the host only rather than to the success output stream - you can use the Out-Host cmdlet.
    • Conversely, to produce data output to the pipeline, use either the Write-Output cmdlet or, preferably, PowerShell's implicit output feature, as shown below; for more information, see this answer.

In order to sort (custom) objects by a given property, simply pass the name of that property to
Sort-Object's (positionally implied) -Property parameter, as Mathias R. Jessen helpfully suggests:

# Using $variable by itself implicitly sends its value through the pipeline.
# It is equivalent to: Write-Output $variable | ...
$variable | Sort-Object sourceDSAcn # same as: ... | Sort-Object -Property sourceDSAcn

Upvotes: 8

Related Questions