Sort-Object

Sort objects by property value.

Syntax
      Sort-Object [[-property] Object[]] [-inputObject psobject] [-culture string]
            [-caseSensitive] [-unique] [-descending][CommonParameters]

Key
   -property Object
       A property or properties to use when sorting.

   -inputObject psobject
       The objects to be sorted. (may be piped)

   -culture string
       The cultural/country configuration to use when sorting.

   -caseSensitive
       Sort UPPER and lower case letters separately.

   -unique 
       Return only the unique values.

   -descending 
       Sort in descending order.

   CommonParameters:
       -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutVariable.

The -Descending parameter applies to all properties. To sort some properties in ascending order and others in decending order, specify the property values with a hashtable like this:
-property @{expression={$_.PropName};Descending=$true}

Examples

List the files in the current directory and sort using the default order (alphabetical by Name):

PS C:\>get-childitem | sort-object

List the files in the current directory and sort by date/time:

PS C:\>get-childitem | sort-object -property LastWriteTime

List the files in the current directory and sort in descending order by the time span between CreationTime and LastWriteTime:

PS C:\>get-childitem *.* | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} | select-object LastWriteTime, CreationTime

"We never sit anything out. We are cups, constantly and quietly being filled. The trick is, knowing how to tip ourselves over and let the Beautiful Stuff out" - Ray Bradbury

Related:

Get-Unique - Get the unique items in a collection
Compare-Object - Compare the properties of objects
ForEach-Object - Loop for each object in the pipeline
Group-Object - Group the objects that contain the same value for a common property
Select-Object - Select properties of objects.
Tee-Object - Send input objects to two places
Where-Object -
Filter the objects passed along the command pipeline.
Equivalent bash command: sort - Sort text files



Back to the Top

© Copyright SS64.com 1999-2010
Some rights reserved