PowerShell 5.1中Get-Service结果被分组,如何取消分组?
解决PowerShell 5.1中Get-Service结果字段分组问题
环境
PowerShell 5.1
问题
执行以下命令调用Get-Service时,返回结果中的名称、状态等字段会以数组形式分组显示,无法得到每个服务对应一条记录的格式:
Invoke-Command -ComputerName $computers { $var1 = Get-Service -Name *ssp* @{ ComputerName = $env:ComputerName DisplayName = $var1.DisplayName Name = $var1.Name Status = $var1.Status StartType = $var1.StartType } }
意外输出
ComputerName Server1 StartType {Automatic, Disabled, Automatic, Disabled} Name {Service1, Service2, Service3} Status {Running, Stopped} ComputerName Server2 StartType {Automatic, Disabled, Automatic, Disabled} Name {Service12, Service23, Service33} Status {Running, Stopped}
期望输出
Server1 Service1 Server1 Service2 Server1 Service3 Server2 Service12 Server2 Service23 Server2 Service33
解决方案
问题根源是$var1是多个服务对象的集合,直接访问集合的属性(如$var1.Name)会返回所有对象对应属性的数组,导致结果分组。需要遍历每个服务对象,为每个服务单独生成记录:
方案1:返回结构化对象(保留所有字段)
Invoke-Command -ComputerName $computers { Get-Service -Name *ssp* | ForEach-Object { [PSCustomObject]@{ ComputerName = $env:ComputerName DisplayName = $_.DisplayName Name = $_.Name Status = $_.Status StartType = $_.StartType } } }
此命令会为每个服务生成一个自定义对象,每个对象对应一条记录,可直接查看或后续处理。
方案2:返回简化文本格式(匹配期望输出)
如果只需要计算机名和服务名的文本输出,可使用字符串格式化:
Invoke-Command -ComputerName $computers { Get-Service -Name *ssp* | ForEach-Object { "{0} {1}" -f $env:ComputerName, $_.Name } }
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

