powershell将WMI查询结果合并到一个表中

时间:2016-07-18 19:24:04

标签: powershell wmi

我想从多台计算机中获取磁盘信息并将其输出。

这有效:

foreach ($args in $file) {
    get-WmiObject win32_logicaldisk -Credential $cre -ComputerName $args -Filter "Drivetype=3"  | 
    ft SystemName,DeviceID,VolumeName,@{Label="Total Size";Expression={$_.Size / 1gb -as [int] }},@{Label="Free Size";Expression={$_.freespace / 1gb -as [int] }} -autosize
}

但输出如下:

SystemName DeviceID VolumeName Total Size Free Size
---------- -------- ---------- ---------- ---------
Computer1  C:       OS                100        31
Computer1  D:       DATA              500       200



SystemName DeviceID VolumeName Total Size Free Size
---------- -------- ---------- ---------- ---------
Computer2  C:       OS                110        48
Computer2  D:       DATA              500       201



SystemName DeviceID VolumeName Total Size Free Size
---------- -------- ---------- ---------- ---------
Computer3  C:       OS                100        38
Computer3  D:       DATA              500       260

我希望他们合并,所以输出如下:

SystemName DeviceID VolumeName Total Size Free Size
---------- -------- ---------- ---------- ---------
Computer1  C:       OS                100        31
Computer1  D:       DATA              500       200
Computer2  C:       OS                110        48
Computer2  D:       DATA              500       201
Computer3  C:       OS                100        38
Computer3  D:       DATA              500       260

我已经考虑过创建一个新对象,但我不确定如何在相同标题下的循环中将WMI查询结果添加到该对象。

1 个答案:

答案 0 :(得分:0)

foreach循环替换为ForEach-Object cmdlet,并将Format-Tableft)移到管道的最后:

$file |ForEach-Object {
    Get-WmiObject win32_logicaldisk -Credential $cre -ComputerName $_ -Filter "Drivetype=3" 
} |Format-Table SystemName,DeviceID,VolumeName,@{Label="Total Size";Expression={$_.Size / 1gb -as [int] }},@{Label="Free Size";Expression={$_.freespace / 1gb -as [int] }} -autosize

(另外,请不要使用$args,这是automatic variable

如果您计划稍后在脚本中使用WMI的输出,请使用Select-Object代替Format-Table

然后在需要显示时使用Format-Table

$LogicalDisks = $file |ForEach-Object {
    Get-WmiObject win32_logicaldisk -Credential $cre -ComputerName $_ -Filter "Drivetype=3" 
} |Select-Object SystemName,DeviceID,VolumeName,@{Label="Total Size";Expression={$_.Size / 1gb -as [int] }},@{Label="Free Size";Expression={$_.freespace / 1gb -as [int] }}

# Do some stuff with $LogicalDisks
# ...

# Time to display the disks to the user
$LogicalDisks |Format-Table -AutoSize