创建和填充哈希表

时间:2014-04-21 21:00:07

标签: arrays powershell

我希望创建一个非锯齿状数组或一个哈希表(我不确定差异,也不知道我需要完成工作)。这是我想要做的。

我想查询多个值的服务器列表,然后将这些值存储到CSV文件中。这是代码。

$allServers = "svr1","svr2","svr3"
$a = @{}
$outData = New-Object PSObject
$allServers | ForEach-Object {
    $cpu = (Get-WmiObject win32_processor -ComputerName $_).length
    $mem = (Get-WmiObject win32_physicalmemory -ComputerName $_).Capacity /1GB
    $outData | Add-Member -Type NoteProperty -Name "SERVERNAME" -Value $_
    $outData | Add-Member -Type NoteProperty -Name "#CPU" -Value $cpu
    $outData | Add-Member -Type NoteProperty -Name "#GBRAM" -Value $mem
    }
Write-Host $outData

我收到错误,因为它似乎正在尝试重复创建相同的条目。是否可以使用列名创建一个空哈希表(或非锯齿状数组),然后只填充值?

1 个答案:

答案 0 :(得分:2)

在循环内创建对象,输出它,并将整个管道的值分配给数组变量:

$allServers = "svr1","svr2","svr3"

$a = $allServers | ForEach-Object {
    $cpu = (Get-WmiObject win32_processor -ComputerName $_).length
    $mem = (Get-WmiObject win32_physicalmemory -ComputerName $_).Capacity /1GB
    $outData = New-Object PSObject
    $outData | Add-Member -Type NoteProperty -Name "SERVERNAME" -Value $_
    $outData | Add-Member -Type NoteProperty -Name "#CPU" -Value $cpu
    $outData | Add-Member -Type NoteProperty -Name "#GBRAM" -Value $mem
    $outData
    }

$a | Export-Csv $path -NoTypeInformation