This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Sorts objects by property values.
Sort-Object [[-Property] <Object[]>] [-Stable] [-Descending] [-Unique] [-InputObject <PSObject>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>]
Sort-Object [[-Property] <Object[]>] -Top <Int32> [-Descending] [-Unique] [-InputObject <PSObject>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>]
Sort-Object [[-Property] <Object[]>] -Bottom <Int32> [-Descending] [-Unique] [-InputObject <PSObject>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>]
TheSort-Object
cmdlet sorts objects in ascending or descending order based on object propertyvalues. If sort properties aren't included in a command, PowerShell uses default sort propertiesof the first input object. If the input object's type has no default sort properties,PowerShell attempts to compare the objects themselves. For more information, see theNotessection.
You can sort objects by a single property or multiple properties. Multiple properties use hashtables to sort in ascending order, descending order, or a combination of sort orders. Properties aresorted as case-sensitive or case-insensitive. Use theUnique parameter to remove duplicatesfrom the output.
This example sorts the files and subdirectories in a directory.
Get-ChildItem -Path C:\Test | Sort-Object
Directory: C:\TestMode LastWriteTime Length Name---- ------------- ------ -----a---- 2/13/2019 08:55 26 anotherfile.txt-a---- 2/13/2019 13:26 20 Bfile.txt-a---- 2/12/2019 15:40 118014 Command.txt-a---- 2/1/2019 08:43 183 CreateTestFile.ps1d----- 2/25/2019 18:25 Filesd----- 2/25/2019 18:24 Logs-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt-a---- 2/12/2019 16:24 23 Zsystemlog.log
TheGet-ChildItem
cmdlet gets the files and subdirectories from the directory specified by thePath parameter,C:\Test
. The objects are sent down the pipeline to theSort-Object
cmdlet.Sort-Object
doesn't specify a property so the output is sorted by the default sort property,Name.
This command displays the files in the current directory by length in ascending order.
Get-ChildItem -Path C:\Test -File | Sort-Object -Property Length
Directory: C:\TestMode LastWriteTime Length Name---- ------------- ------ -----a---- 2/13/2019 13:26 20 Bfile.txt-a---- 2/12/2019 16:24 23 Zsystemlog.log-a---- 2/13/2019 08:55 26 anotherfile.txt-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt-a---- 2/1/2019 08:43 183 CreateTestFile.ps1-a---- 2/12/2019 15:40 118014 Command.txt
TheGet-ChildItem
cmdlet gets the files from the directory specified by thePath parameter.TheFile parameter specifies thatGet-ChildItem
only gets file objects. The objects are sentdown the pipeline to theSort-Object
cmdlet.Sort-Object
uses theLength parameter to sortthe files by length in ascending order.
This example displays processes with the highest memory usage based on their working set (WS) size.
Get-Process | Sort-Object -Property WS | Select-Object -Last 5
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 136 193.92 217.11 889.16 87492 8 OUTLOOK 112 347.73 297.02 95.19 106908 8 Teams 206 266.54 323.71 37.17 60620 8 MicrosoftEdgeCP 35 552.19 549.94 131.66 6552 8 Code 0 1.43 595.12 0.00 2780 0 Memory Compression
TheGet-Process
cmdlet gets the list of processes running on the computer. The process objects aresent down the pipeline to theSort-Object
cmdlet.Sort-Object
uses theProperty parameter tosort the objects byWS. The objects are sent down the pipeline to theSelect-Object
cmdlet.Select-Object
uses theLast parameter to specify the last five objects, which are the objectswith the highestWS usage.
In PowerShell 6, theSort-Object
parameterBottom is an alternative toSelect-Object
. Forexample,Get-Process | Sort-Object -Property WS -Bottom 5
.
This command sorts the PowerShell session'sHistoryInfo objects using theId property. EachPowerShell session has its own command history.
Get-History | Sort-Object -Property Id -Descending
Id CommandLine -- ----------- 10 Get-Command Sort-Object -Syntax 9 $PSVersionTable 8 Get-Command Sort-Object -Syntax 7 Get-Command Sort-Object -ShowCommandInfo 6 Get-ChildItem -Path C:\Test | Sort-Object -Property Length 5 Get-Help Clear-History -Online 4 Get-Help Clear-History -Full 3 Get-ChildItem | Get-Member 2 Get-Command Sort-Object -Syntax 1 Set-Location C:\Test\
TheGet-History
cmdlet gets the history objects from the current PowerShell session. The objectsare sent down the pipeline to theSort-Object
cmdlet.Sort-Object
uses thePropertyparameter to sort the objects byId. TheDescending parameter sorts the command history fromnewest to oldest.
This example uses two properties to sort the objects,Status andDisplayName.Status issorted in descending order andDisplayName is sorted in ascending order.
A hash table is used to specify theProperty parameter's value. The hash table uses anexpression to specify the property names and sort orders. For more information about hash tables,seeabout_Hash_Tables.
TheStatus property used in the hash table is an enumerated property. For more information, seeServiceControllerStatus.
Get-Service | Sort-Object -Property @{Expression = "Status"; Descending = $true}, @{Expression = "DisplayName"; Descending = $false}
Status Name DisplayName------ ---- -----------Running Appinfo Application InformationRunning BthAvctpSvc AVCTP serviceRunning BrokerInfrastru... Background Tasks Infrastructure Ser...Running BDESVC BitLocker Drive Encryption ServiceRunning CoreMessagingRe... CoreMessagingRunning VaultSvc Credential ManagerRunning DsSvc Data Sharing ServiceRunning Dhcp DHCP Client...Stopped ALG Application Layer Gateway ServiceStopped AppMgmt Application ManagementStopped BITS Background Intelligent Transfer Ser...Stopped wbengine Block Level Backup Engine ServiceStopped BluetoothUserSe... Bluetooth User Support Service_14fb...Stopped COMSysApp COM+ System ApplicationStopped smstsmgr ConfigMgr Task Sequence AgentStopped DeviceInstall Device Install ServiceStopped MSDTC Distributed Transaction Coordinator
TheGet-Service
cmdlet gets the list of services on the computer. The service objects are sentdown the pipeline to theSort-Object
cmdlet.Sort-Object
uses theProperty parameter with ahash table to specify the property names and sort orders. TheProperty parameter is sorted bytwo properties,Status in descending order andDisplayName in ascending order.
Status is an enumerated property.Stopped has a value of1 andRunning has a valueof4. TheDescending parameter is set to$true
so thatRunning processes are displayedbeforeStopped processes.DisplayName sets theDescending parameter to$false
to sortthe display names in alphabetical order.
This command sorts text files in descending order by the time span betweenCreationTime andLastWriteTime.
Get-ChildItem -Path C:\Test\*.txt | Sort-Object -Property {$_.CreationTime - $_.LastWriteTime} | Format-Table CreationTime, LastWriteTime, FullName
CreationTime LastWriteTime FullName------------ ------------- --------11/21/2018 12:39:01 2/26/2019 08:59:36 C:\Test\test2.txt12/4/2018 08:29:41 2/26/2019 08:57:05 C:\Test\powershell_list.txt2/20/2019 08:15:59 2/26/2019 12:09:43 C:\Test\CreateTestFile.txt2/20/2019 08:15:59 2/26/2019 12:07:41 C:\Test\Command.txt2/20/2019 08:15:59 2/26/2019 08:57:52 C:\Test\ReadOnlyFile.txt11/29/2018 15:16:50 12/4/2018 16:16:24 C:\Test\LogData.txt2/25/2019 18:25:11 2/26/2019 12:08:47 C:\Test\Zsystemlog.txt2/25/2019 18:25:11 2/26/2019 08:55:33 C:\Test\Bfile.txt2/26/2019 08:46:59 2/26/2019 12:12:19 C:\Test\LogFile3.txt
TheGet-ChildItem
cmdlet uses thePath parameter to specify the directoryC:\Test
and allof the*.txt
files. The objects are sent down the pipeline to theSort-Object
cmdlet.Sort-Object
uses theProperty parameter with a scriptblock to determine each files time spanbetweenCreationTime andLastWriteTime.
This example shows how to sort a list from a text file. The original file is displayed as anunsorted list.Sort-Object
sorts the contents and then sorts the contents with theUniqueparameter that removes duplicates.
# All items unsortedGet-Content -Path C:\Test\ServerNames.txt
localhostserver01server25LOCALHOSTServer19server3localhost
# All items sortedGet-Content -Path C:\Test\ServerNames.txt | Sort-ObjectlocalhostLOCALHOSTlocalhostserver01Server19server25server3
# Unique filtered items sortedGet-Content -Path C:\Test\ServerNames.txt | Sort-Object -Unique
localhostserver01Server19server25server3
TheGet-Content
cmdlet uses thePath parameter to specify the directory and filename. ThefileServerNames.txt
contains an unsorted list of computer names.
TheGet-Content
cmdlet uses thePath parameter to specify the directory and filename. ThefileServerNames.txt
contains an unsorted list of computer names. The objects are sent down thepipeline to theSort-Object
cmdlet.Sort-Object
sorts the list in the default order, ascending.
TheGet-Content
cmdlet uses thePath parameter to specify the directory and filename. ThefileServerNames.txt
contains an unsorted list of computer names. The objects are sent down thepipeline to theSort-Object
cmdlet.Sort-Object
uses theUnique parameter to removeduplicate computer names. The list is sorted in the default order, ascending.
This example shows how to sort a text file that contains string objects as integers. You can sendeach command down the pipeline toGet-Member
and verify that the objects are strings instead ofintegers. For these examples, theProductId.txt
file contains an unsorted list of product numbers.
In the first example,Get-Content
gets the contents of the file and pipes lines to theSort-Object
cmdlet.Sort-Object
sorts the string objects in ascending order.
# String sortedGet-Content -Path C:\Test\ProductId.txt | Sort-Object
0112345150022800350041005006200778899999
# Integer sortedGet-Content -Path C:\Test\ProductId.txt | Sort-Object {[int]$_}
0127788500150028003500410062001234599999
In the second example,Get-Content
gets the contents of the file and pipes lines to theSort-Object
cmdlet.Sort-Object
uses a script block to convert the strings to integers. In thesample code,[int]
converts the string to an integer and$_
represents each string as it comesdown the pipeline. The integer objects are sent down the pipeline to theSort-Object
cmdlet.Sort-Object
sorts the integer objects in numeric order.
When you use theTop,Bottom, orStable parameters, the sorted objects are delivered inthe order they were received bySort-Object
when the sort criteria are equal. In this example, weare sorting the numbers one through 20 by the their value 'modulo 3'. The modulo value ranges fromzero to two.
1..20 |Sort-Object {$_ % 3}
1831561291161310741911814517220
1..20 |Sort-Object {$_ % 3} -Stable
3691215181471013161925811141720
The output from the first sort is correctly grouped by the modulus value but the individual itemsaren't sorted within the modulus range. The second sort uses theStable option to return astable sort.
If you want to sort by multiple properties, separate the properties by commas.
Get-ChildItem -Path C:\Test | Sort-Object Length,Name
Directory: C:\TestMode LastWriteTime Length Name---- ------------- ------ -----a--- 13/10/2021 22:16 2 File01.txt-a--- 13/10/2021 22:16 2 File03.txt-a--- 13/10/2021 22:18 64 File02.txt-a--- 13/10/2021 22:18 64 File04.txt
TheGet-ChildItem
cmdlet gets the files from the directory specified by thePath parameter.The objects are sent down the pipeline to theSort-Object
cmdlet.Sort-Object
uses theLength andName parameter to sort the files by length in ascending order. SinceFile01.txt
andFile03.txt
have the same length, they're further sorted by their propertyName.
Beginning in PowerShell 6,Sort-Object
supports sorting ofhashtable input by key values. Thefollowing example sorts an array of hashtables by the value of each hashtable'sweight
key.
@( @{ name = 'a' ; weight = 7 } @{ name = 'b' ; weight = 1 } @{ name = 'c' ; weight = 3 } @{ name = 'd' ; weight = 7 }) | Sort-Object -Property weight -OutVariable Sorted$Sorted | ForEach-Object -Process { "{0}: {1}" -f $_.name, $_.weight }
Name Value---- -----Weight 1Name bWeight 3Name cWeight 7Name aWeight 7Name db: 1c: 3a: 7d: 7
Specifies the number of objects to get from the end of a sorted object array. This results in astable sort.
This parameter was introduced in PowerShell 6.0.
Type: | Int32 |
Default value: | None |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | True |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
Indicates that the sort is case-sensitive. By default, sorts aren't case-sensitive.
Type: | SwitchParameter |
Default value: | Case-insensitive |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | False |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
Specifies the cultural configuration to use for sorts. UseGet-Culture
to display the system'sculture configuration.
Type: | String |
Default value: | None |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | False |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
Indicates thatSort-Object
sorts the objects in descending order. The default is ascending order.
To sort multiple properties with different sort orders, use a hash table. For example, with a hashtable you can sort one property in ascending order and another property in descending order.
Type: | SwitchParameter |
Default value: | Ascending |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | False |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
To sort objects, send them down the pipeline toSort-Object
. If you use theInputObjectparameter to submit a collection of items,Sort-Object
receives one object that represents thecollection. Because one object can't be sorted,Sort-Object
returns the entire collectionunchanged.
Type: | PSObject |
Default value: | None |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | False |
Value from pipeline: | True |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
Specifies the property names thatSort-Object
uses to sort the objects. Wildcards are permitted.Objects are sorted based on the property values. If you don't specify a property,Sort-Object
sorts based on default properties for the object type or the objects themselves.
Use commas to separate multiple properties. Multiple properties can be sorted in ascending order,descending order, or a combination of sort orders. When you specify multiple properties, theobjects are sorted by the first property. If multiple objects have the same value for the firstproperty, those objects are sorted by the second property. This process continues until there areno more specified properties or no groups of objects.
TheProperty parameter's value can be a calculated property. To create a calculated property,use a scriptblock or a hashtable.
Valid keys for a hash table are as follows:
Expression
-<string>
or<script block>
Ascending
orDescending
-<boolean>
For more information, seeabout_Calculated_Properties.
Type: | Object[] |
Default value: | Default properties |
Supports wildcards: | True |
DontShow: | False |
Position: | 0 |
Mandatory: | False |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
The sorted objects are delivered in the order they were received when the sort criteria are equal.
This parameter was added in PowerShell v6.2.0.
Type: | SwitchParameter |
Default value: | None |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | False |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
Specifies the number of objects to get from the start of a sorted object array. This results in astable sort.
This parameter was introduced in PowerShell 6.0.
Type: | Int32 |
Default value: | None |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | True |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
Indicates thatSort-Object
eliminates duplicates and returns only the unique members of thecollection. The first instance of a unique value is included in the sorted output.
Unique is case-insensitive. Strings that only differ by character case are considered the same.For example, character and CHARACTER.
Type: | SwitchParameter |
Default value: | All |
Supports wildcards: | False |
DontShow: | False |
Position: | Named |
Mandatory: | False |
Value from pipeline: | False |
Value from pipeline by property name: | False |
Value from remaining arguments: | False |
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable,-InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable,-ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, seeabout_CommonParameters.
You can pipe the objects to be sorted to this cmdlet.
This cmdlet returns the sorted objects.
PowerShell includes the following aliases forSort-Object
:
sort
TheSort-Object
cmdlet sorts objects based on properties specified in the command or the defaultsort properties for the object type. Default sort properties are defined using thePropertySet
namedDefaultKeyPropertySet
in atypes.ps1xml
file. For more information, seeabout_Types.ps1xml.
If an object doesn't have one of the specified properties, the property value for that object isinterpreted bySort-Object
asNull and placed at the end of the sort order.
When no sort properties are available, PowerShell attempts to compare the objects themselves.Sort-Object
uses theCompare method for each property. If a property doesn't implementIComparable, the cmdlet converts the property value to a string and uses theCompare methodforSystem.String. For more information, seePSObject.CompareTo(Object) Method.
If you sort on an enumerated property such asStatus,Sort-Object
sorts by the enumerationvalues. For Windows services,Stopped has a value of1 andRunning has a value of4.Stopped is sorted beforeRunning because of the enumerated values. For more information,seeServiceControllerStatus.
The performance of the sorting algorithm is slower when doing a stable sort.
Was this page helpful?
Was this page helpful?