Powershell脚本在for循环中以逗号分隔的值获取输出

时间:2019-04-14 17:15:31

标签: powershell

尝试使用for循环在我的脚本中输入服务器列表,然后需要以逗号分隔的格式显示结果。

输入服务器列表

$s1 = (get-content .\s1.txt)
foreach($s2 in $s1){
    $object = New-Object -TypeName PSObject

    $NumberoflogicalProcessors = (gwmi win32_processor -computername $s2 |measure -Property NumberoflogicalProcessors -Sum).Sum
    $CPUCore = (gwmi win32_processor -computername $s2 |measure -Property  numberOfCores -Sum).Sum

    $object | Add-Member -MemberType NoteProperty -Name "CPU Logical processors" -Value $NumberoflogicalProcessors
    $object | Add-Member -MemberType NoteProperty -Name "CPU Core" -Value $CPUCore
    $List+= $object
}
return $List

$str1 = "NumberoflogicalProcessors"+","+"CPUCore"
$str2 = $NumberoflogicalProcessors.ToString() + "," + $CPUCore.ToString()
return $str1 + "`n" + $str2

预期输出:

row1(header)
row2(server1 values)
row2(server2 values)

示例:

NumberoflogicalProcessors, CPUCore
2, 5
4, 3
so on.......

1 个答案:

答案 0 :(得分:3)

更简洁,更易读的东西是这样的:

$s1 = Get-Content -Path .\s1.txt
$List = foreach ($s2 in $s1) {
    $CPUCore = Get-CimInstance -ClassName CIM_Processor  -ComputerName  $s2 

    [PSCustomObject]@{
        ComputerName = $s2
        PhysicalCores = $CPUCore.NumberOfCores
        LogicalCores  = $CPUCore.NumberOfLogicalProcessors
    }
}
$List
$List | Export-Csv -Path .\s1List.csv -Delimiter ',' -NoTypeInformation

您不需要在一个循环中运行两次WMI或CIM cmdlet。