Acerbity
Acerbity

Reputation: 527

Creating and populating a hash table

I am looking to create either a non-jagged array or a hash table (I am not sure the difference nor what I need to get the job done). Here is what I am trying to do.

I would like to query a list of servers for several values and then store those values for output to a CSV file. Here is the code.

$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

I am getting errors because it seems like it is trying to create the same entries repeatedly. Is it possible to make an empty hash table (or non-jagged array) with column names and then just populate values?

Upvotes: 2

Views: 559

Answers (1)

KevinD
KevinD

Reputation: 3163

Create the object inside the loop, output it, and assign the value of the whole pipeline to your array variable:

$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

Upvotes: 3

Related Questions