如何在 PowerShell 中使用 Group-Object cmdlet?
顧名思義, Group-Object 用於對類似屬性進行分組。
示例
Get-Service | Group-Object Status
輸出
Count Name Group
----- ---- -----
160 Stopped {AarSvc_8f3023, AdobeFlashPlayerUpdateSvc, AJR outer, ALG...}
130 Running {AdobeARMservice, Appinfo, AudioEndpointBuilder, Audiosrv...}上述輸出根據狀態(“已停止”和“正在執行”)進行分組。共有 160 項服務處於已停止狀態,130 項處於正在執行狀態。
同樣,你也可以使用啟動型別屬性對組進行篩選。
Get-Service | Group-Object StartType
輸出
PS C:\WINDOWS\system32> Get-Service | Group-
Object StartType
Count Name Group
----- ---- -----
197 Manual {AarSvc_8f3023, AdobeFlashPlayerUpdateSvc, A JRouter, ALG...}
84 Automatic {AdobeARMservice, AudioEndpointBuilder, Audi , AVP20.0...}
9 Disabled {AppVClient, NetTcpPortSharing, RemoteAccess , RemoteRegistry...}如果你只需要計數和名稱屬性,請使用 − NoElement 引數。
Get-Service | Group-Object StartType -NoElement
輸出
Count Name ----- ---- 197 Manual 84 Automatic 9 Disabled
如果你需要組的值,則需要首先將其轉換為雜湊表,如下所示。
Get-Service | Group-Object Status –AsHashTable -AsString
輸出
Name Value
---- -----
Stopped {AarSvc_8f3023, AdobeFlashPlayerUpdateSvc, AJRo uter, ALG...}
Running {AdobeARMservice, Appinfo, AudioEndpointBuilder , Audiosrv...}現在我們對正在執行的服務感興趣,因此將服務的輸出儲存在變數中,然後我們將使用“正在執行”值來檢索所需輸出。
$services = Get-Service | Group-Object Status -AsHashTable -AsString $services.Running
輸出
PS C:\WINDOWS\system32> $services.Running Status Name DisplayName ------ ---- ----------- Running AdobeARMservice Adobe Acrobat Update Service Running Appinfo Application Information Running AudioEndpointBu... Windows Audio Endpoint Builder Running Audiosrv Windows Audio Running AVP20.0 Kaspersky Anti-Virus Service 20.0 Running BFE Base Filtering Engine Running BITS Background Intelligent Transfer Ser... Running Bluetooth Devic... Bluetooth Device Monitor Running Bluetooth OBEX ... Bluetooth OBEX Service Running BrokerInfrastru... Background Tasks Infrastructure Ser... Running Browser Computer Browser Running BTAGService Bluetooth Audio Gateway Service Running BthAvctpSvc AVCTP service Running bthserv Bluetooth Support Service Running camsvc Capability Access Manager Service Running cbdhsvc_8f3023 Clipboard User Service_8f3023 Running CDPSvc Connected Devices Platform Service Running CDPUserSvc_8f3023 Connected Devices Platform User Ser... Running ClickToRunSvc Microsoft Office Click-to-Run Service Running ClipSVC Client License Service (ClipSVC)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP