Order Your Output by Easily Sorting Objects in PowerShell

★★★★★
★★★★
★★★
★★
January 10, 2012 by The Scripting Guys // 9 Comments

Summary: Much of the time, there is no guarantee to the order in which Windows PowerShell returns objects. This blog explains how to fix that issue.

Hey, Scripting Guy! I have a problem with Windows PowerShell. It seems that it deliberately randomizes the output. I mean, there seems to be no rhyme or reason to the way that information is returned from a cmdlet. Am I alone in this frustration, or is there some secret sauce that I am missing? Windows PowerShell is cool, but if I always have to put data into an Excel spreadsheet just to sort it, then it is not much better than VBScript in my mind. Help me, oh fount of Windows PowerShell wisdom.

—CD

Hello CD,

Microsoft Scripting Guy, Ed Wilson, is here. The other day, the Scripting Wife and I were at the first ever Windows PowerShell User Group meeting in Charlotte, North Carolina. It was really cool. We love being able to interact with people who love Windows PowerShell as much as we do. Next month, we are having a script-club type of meeting; we encourage people to show up with the Windows PowerShell scripts they are working on, so it will be a show-and-tell type of meeting.

Use Sort-Object to organize output

Anyway, after the user group meeting, when we were all standing around, one of the attendees came up to me and asked me in what order Windows PowerShell returns information. The answer is that there is no guarantee of return order in most cases. The secret sauce is to use the built-in sorting mechanism from Windows PowerShell itself. In the image that follows, the results from the Get-Process cmdlet appear to sort on the ProcessName property.

One could make a good argument that the processes should sort on the process ID (PID) or on the amount of CPU time consumed, or on the amount of memory utilized. In fact, it is entirely possible that for each property supplied by the Process object, someone has a good argument for sorting on that particular property. Luckily, custom sorting is easy to accomplish in Windows PowerShell. To sort returned objects in Windows PowerShell, pipe the output from one cmdlet to the Sort-Object cmdlet. This technique is shown here where the Sort-Object cmdlet sorts the Process objects that are returned by the Get-Process cmdlet.

Get-Process | Sort-Object id

The command to sort the Process objects on the ID property and the output associated with that command are shown in the image that follows.

Reversing the sort order

By default, the Sort-Object cmdlet performs an ascending sort—the numbers range from small to large. To perform a descending sort requires utilizing the Descending switch.

Note:  There is no Ascending switch for the Sort-Object cmdlet because that is the default behavior.

To arrange the output from the Get-Process cmdlet such that the Process objects appear from largest process ID to the smallest (the smallest PID is always 0—the Idle process), choose the ID property to sort on, and use the Descending switch as shown here:

Get-Process | Sort-Object id –Descending

The command to perform a descending sort of processes based on the process ID, and the output associated with that command are shown in the image that follows.

When you use the Sort-Object cmdlet to sort output, keep in mind that the first position argument is the property or properties upon which to sort. Because Property is the default means that using the name Property in the command is optional. Therefore, the following commands are equivalent:

Get-Process | Sort-Object id –Descending

Get-Process | Sort-Object -property id –Descending

In addition to using the default first position for the Property argument, the Sort-Object cmdlet is aliased by sort. By using gps as an alias for the Get-Process cmdlet, sort as an alias for Sort-Object, and a partial parameter of des for Descending, the syntax of the command is very short. This short version of the command is shown here.

gps | sort id –des

Sorting multiple properties at once

The Property parameter of the Sort-Object cmdlet accepts an array (more than one) of properties upon which to sort. This means that I can sort on the process name, and then sort on the working set of memory that is utilized by each process (for example). When supplying multiple property names, the first property sorts, then the second property sorts.

The resulting output may not always meet expectations, and therefore, may require a bit of experimentation. For example, the command that follows sorts the process names in a descending order. When that sort completes, the command does an additional sort on the WorkingSet(ws is the alias) property. However, this second sort is only useful when there happen to be multiple processes with the same name (such as the svchost process). The command that is shown here is an example of sorting on multiple properties.

Get-Process | Sort-Object -Property name, ws –Descending

The figure that is shown here illustrates the output from the command to sort Process objects based on name and ws properties.

When the name and ws properties reverse order in the command, the resulting output is not very useful because the only sorting of thename property happens when multiple processes have an identical working set of memory. The command that is shown here reverses the order of the WorkingSet and the process name properties.

Get-Process | Sort-Object -Property ws, name –Descending

The output that is shown here shows that there is very little grouping of process names. In this example, adding the name property does not add much value to the command.

Sorting and returning unique items

At times, I might want to see how many different processes are running on a system. To do this, I can filter duplicate process names by using the Unique switch. To count the number of unique processes that are running on a system, I pipe the results from the Sort-Object cmdlet to the Measure-Object cmdlet. This command is shown here.

Get-Process | Sort-Object -Property name -Descending -Unique | measure-object

To obtain a baseline that enables me to determine the number of duplicate processes, I drop the Unique switch. This command is shown here.

Get-Process | Sort-Object -Property name -Descending | measure-object

Performing a case sensitive sort

One last thing to discuss when sorting items is the CaseSensitive switch. When used, the CaseSensitive switch sorts lowercase letters first, then uppercase. The following commands illustrate this.

$a = “Alpha”,”alpha”,”bravo”,”Bravo”,”Charlie”,”charlie”,”delta”,”Delta”

$a | Sort-Object –CaseSensitive

When the two previous commands run, the output places the lowercase version of the word prior to the uppercase version. This output appears in the figure that follows.

CD, that is all there is to sorting with Windows PowerShell. Pipeline Week will continue tomorrow when I will talk about grouping things with Windows PowerShell.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerShell 中进行列表展示的排序-倒序的更多相关文章

  1. python中对列表元素大小排序(冒泡排序法和选择排序法)

    前言:排序(Sorting) 是计算机程序设计中的一种重要操作,它的功能是将一个数据元素(或记录)的任意序列,重新排列成一个关键字有序的序列.本文主要讲述python中经常用的两种排序算法,选择排序法 ...

  2. JAVA实现按列表中元素的时间字段排序

    JAVA代码实现按列表中元素的时间字段排序 导语: 工作中遇到一个问题,调用第三方接口返回的数据没有按时间倒序排列,测试说要加,然后在网上找到一个解决办法,这里记录一下 需求: 如下图列表,按生日进行 ...

  3. 列表中字符串按照某种规则排序的方法(python)

    有时候处理数据时,想要按照字符串中的数字的大小进行排序. 譬如,存在一组记录文件,分别为‘1.dat’,'2.dat'... 当我把该文件夹中的所有记录文件名读到一个列表中,这些字符串的排列方式为: ...

  4. Python中对列表排序实例

    Python中对列表排序实例 发布时间:2015-01-04 09:01:50 投稿:junjie 这篇文章主要介绍了Python中对列表排序实例,本文给出了9个List的排序实例,需要的朋友可以参考 ...

  5. 2019年6月12日——开始记录并分享学习心得——Python3.7中对列表进行排序

    Python中对列表的排序按照是排序是否可以恢复分为:永久性排序和临时排序. Python中对列表的排序可以按照使用函数的不同可以分为:sort( ), sorted( ), reverse( ). ...

  6. JSP中列表展示,隔行变色以及S标签的使用

    1.java代码 /** * 列表展示,隔行变色以及S标签的使用 * * @return */ public String list() { List<User> list = new A ...

  7. python中对列表的排序

    1.sort()对列表永久性的排序,首字母按照字母表的顺序排列 book=['python','java','c++','web'] book.sort() print(book) 结果如下: 2.向 ...

  8. django学习-27.admin管理后台里:对列表展示页面的数据展示进行相关优化

    目录结构 1.前言 2.完整的操作步骤 2.1.第一步:查看ModelAdmin类和BaseModelAdmin类的源码 2.2.第二步:查看表animal对应的列表展示页面默认的数据展示 2.3.第 ...

  9. ListView列表拖拽排序

    ListView列表拖拽排序能够參考Android源代码下的Music播放列表,他是能够拖拽的,源代码在[packages/apps/Music下的TouchInterceptor.java下]. 首 ...

随机推荐

  1. C#进程间通讯技术-整理。

    原文:C#进程间通讯技术-整理. 扩展阅读:http://www.cnblogs.com/joye-shen/archive/2012/06/16/2551864.html 一.进程间通讯的方式 1) ...

  2. mysql sql优化<1>

    <pre name="code" class="html">explain SELECT t.* FROM ( SELECT t1.sn AS cl ...

  3. NOI2013 UOJ122 向量内积

    神题...... 还是大神讲得比较清晰~orz http://dffxtz.logdown.com/posts/197950-noi2013-vector-inner-product 启发题:poj3 ...

  4. VS2012/2013编辑器问题

    1. Visual Studio 2013 'Could not evaluate Expression' Debugger Abnormality 解决办法:http://weblog.west-w ...

  5. 简学LINGO(三)——实例篇

    1. 装配线平衡模型 一个装配线含有一系列的工作站.在终于产品的加工过程中每一个工作站运行一种或者是几种特定的任务.装配线周期是指全部工作站完毕分配给他们各自任务所花费时间的最大值.平衡装配线的目标是 ...

  6. sql server 2008 中的架构(schame)理解

    机构是属于数据库里面的.在一个数据库中,每一张表都属于一个架构,架构就像是命名空间,把数据库中的表分成不同的组,一个组就是一个命名空间,方便管理

  7. Oracle 监听配置详解(转载)

        使用ORACLE的SQL*Net V.2连接客户机和服务器,需配置每个客户机和服务器.在服务器上需配置的文件有:listener.ora./etc/services,在客户机上需配置tnsna ...

  8. Stm32高级定时器(一)

    Stm32高级定时器(一) 1 定时器的用途 2 高级定时器框图 3 时基单元 4 通道 1 定时器的用途 已知一个波形求另一个未知波形(信号长度和占空比) 已知波形的信号长度和占空比产生一个相应的波 ...

  9. My way on Linux - [Shell基础] - Bash Shell中判断文件、目录是否存在或者判断其是否具有某类属性(权限)的常用方法

    Conditional Logic on Files # 判断文件是否存在及文件类型 -a file exists. #文件存在 -b file exists and is a block speci ...

  10. [.NET | 發佈] 如何指定固定的目錄給程式調用的外部DLL?

    1.OverView 一般程式只會查找與主程式同目錄的DLL檔案 解決方案主要可以參考這篇:http://support.microsoft.com/kb/837908 2.實作app.config方 ...