使用Sort-Object和Group-Object可以對管道結果進行分組。
其實每條命令執行后的結果已經排過序了。例如通過ls 查看文件列表,默認會根據Name屬性進行排序,但是你可以通過指定屬性進行排序例如:
PS C:Powershell> ls | Sort-Object LengthMode LastWriteTime Length Name---- ------------- ------ -----a--- 2011/11/28 15:30 63 ping.bat-a--- 2011/12/2 18:47 140 test.ps1-a--- 2011/11/28 16:42 170 test.vbs-a--- 2011/11/28 11:12 186 LogoTestConfig.xml-a--- 2011/11/23 17:37 242 test.txt-a--- 2011/11/25 11:20 556 employee.xml
這樣默認會根據length進行升序排序,如果要降序排列,可是使用Descending選項。
PS C:Powershell> ls | Sort-Object Length -DescendingMode LastWriteTime Length Name---- ------------- ------ -----a--- 2011/11/24 17:44 735892 Powershell_Cmdlets.html-a--- 2011/11/24 18:30 67580 a.html-a--- 2011/11/24 20:04 26384 a.txt-a--- 2011/11/29 19:23 21466 function.ps1-a--- 2011/11/24 20:26 12060 alias-a--- 2011/11/24 17:37 7420 name.html
給對象和哈希表進行排序
如果要完成主要關鍵字降序,次要關鍵字升序的排序,可能首先想到的是:
PS C:Powershell> Dir | Sort-Object Length, Name -descending, -ascendingSort-Object : 找不到接受實際參數“System.Object[]”的位置形式參數。所在位置 行:1 字符: 18+ Dir | Sort-Object <<<< Length, Name -descending, -ascending + CategoryInfo : InvalidArgument: (:) [Sort-Object], ParameterBin dingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell .Commands.SortObjectCommand
但是上面的方法行不通,可是這樣操作:
PS C:Powershell> Dir | Sort-Object @{expression="Length";Descending=$true},@{expression="Name";Ascending=$true} 目錄: C:PowershellMode LastWriteTime Length Name---- ------------- ------ -----a--- 2011/11/24 17:44 735892 Powershell_Cmdlets.html-a--- 2011/11/24 18:30 67580 a.html-a--- 2011/11/24 20:04 26384 a.txt-a--- 2011/11/29 19:23 21466 function.ps1-a--- 2011/11/24 20:26 12060 alias-a--- 2011/11/24 17:37 7420 name.html-a--- 2011/12/14 11:22 3460 ls.html-a--- 2011/11/30 16:04 2556 psdrive.html-a--- 2011/11/25 11:20 556 employee.xml-a--- 2011/11/23 17:37 242 test.txt-a--- 2011/11/28 11:12 186 LogoTestConfig.xml-a--- 2011/11/28 16:42 170 test.vbs-a--- 2011/12/2 18:47 140 test.ps1
對數據進行分組
如果想查看當前關閉和開啟的所有服務,并且通過狀態進行分組。可是使用:
PS C:Powershell> Get-Service | Group-Object StatusCount Name Group----- ---- ----- 87 Running {System.ServiceProcess.ServiceController, System.ServiceProcess.S erviceController, System.ServiceProcess.ServiceController, System .ServiceProcess.ServiceController...} 88 Stopped {System.ServiceProcess.ServiceController, System.ServiceProcess.S erviceController, System.ServiceProcess.ServiceController, System .ServiceProcess.ServiceController...}
新聞熱點
疑難解答