无法将输出格式化为CSV

时间:2019-05-15 15:25:22

标签: powershell export-to-csv

我无法使用echo功能将PS输出转换为CSV格式。我需要收集有关多个服务器的硬件信息,并从Internet获得此脚本。我对其进行了修改,以仅收集必要的信息,例如计算机名,硬盘空间,CPU详细信息和RAM。

下面是我的代码:

$ArrComputers = "PC17"
Clear-Host
foreach ($Computer in $ArrComputers) {
    $computerSystemRam = Get-WmiObject Win32_ComputerSystem -Computer $Computer |
                         select @{n="Ram";e={[math]::Round($_.TotalPhysicalMemory/1GB,2)}} |
                         FT -HideTableHeaders -AutoSize
    $computerCPU = Get-WmiObject Win32_Processor -Computer $Computer |
                   select Name |
                   FT -HideTableHeaders
    $computerCPUCores = Get-WmiObject Win32_Processor -Computer $Computer |
                        select NumberOfLogicalProcessors |
                        FT -HideTableHeaders -AutoSize 
    $computerC = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'C:'" -ComputerName $Computer |
                 select @{n="Size";e={[math]::Round($_.Size/1GB,2)}} |
                 FT -HideTableHeaders -AutoSize 
    $computerD = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'D:'" -ComputerName $Computer |
                 select @{n="Size";e={[math]::Round($_.Size/1GB,2)}} |
                 FT -HideTableHeaders -AutoSize 
    $computerE = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'E:'" -ComputerName $Computer |
                 select @{n="Size";e={[math]::Round($_.Size/1GB,2)}} |
                 FT -HideTableHeaders -AutoSize 
    echo $computer,$computerC,$computerD,$computerE,$computerSystemRam,$computerCPU,$computerCPUCores
}

我的输出为

PC17
99.9
12
537.11
15.98
Intel(R) Xeon(R) CPU E5-2630 0 @ 2.30GHz
12

我需要的是将输出作为逗号分隔的值,如下所示

PC17,99.9,12,537.11,15.98,Intel(R) Xeon(R) CPU E5-2630 0 @ 2.30GHz,12

以便我可以在Excel中打开它。请让我知道这里的问题是什么?或其他任何替代解决方案,以使输出为.csv。

1 个答案:

答案 0 :(得分:1)

删除Format-Table,使用ExpandProperty并从数组中选择合适的属性,

此外,我使用-f来格式化csv,请看区别:

foreach ($Computer in $ArrComputers) 
{
    $computerSystemRam = get-wmiobject Win32_ComputerSystem -Computer $Computer | select @{n="Ram";e={[math]::Round($_.TotalPhysicalMemory/1GB,2)}}
    $computerCPU = get-wmiobject Win32_Processor -Computer $Computer | select -ExpandProperty Name
    $computerCPUCores = get-wmiobject Win32_Processor -Computer $Computer | select -ExpandProperty NumberOfLogicalProcessors
    $computerC = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'C:'" -ComputerName $Computer | select @{n="Size";e={[math]::Round($_.Size/1GB,2)}}
    $computerD = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'D:'" -ComputerName $Computer | select @{n="Size";e={[math]::Round($_.Size/1GB,2)}}
    $computerE = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'E:'" -ComputerName $Computer | select @{n="Size";e={[math]::Round($_.Size/1GB,2)}}
    "{0},{1},{2},{3},{4},{5},{6}" -f $computer,$computerC.Size,$computerD.Size,$computerE.Size,$computerSystemRam.Ram,$computerCPU,$computerCPUCores
}