如何在 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