将循环中的输出添加到散列表powershell

时间:2013-08-23 15:27:13

标签: powershell hash foreach add

我有以下代码,

#Pull the number of Physical Drives
$phy = $datafile.GetEnumerator()|Where-Object {$_.name -like "*Physical*"} 
[array]$phydisks = ($phy.name | Sort-Object )   
#For each of these drives work work out the physical make up of the disk
$drives= ForEach($_ in $phydisks){
    $cylinders = $datafile["$_"]["Cylinders"]
    $head = $datafile["$_"]["TracksPerCylinder"]
    $sectors = $datafile["$_"]["SectorsPerTrack"]
    $bytespersector = $datafile["$_"]["BytesPerSector"]
    #Convert the output to gigabites and round up the the next decimal place
    $physicaldrivegb = ((([int]$cylinders * [int]$head * [int]$sectors * [int]$bytespersector) / 1024) / 1024) /1024
    $physicaldrivesize = [math]::Round($physicaldrivegb,1)
} 

$vmwarefile = @{
    ServerName=$servername;
    Memory = $servermemorymb;
    number_of_processors = $processorcount;
    'number_of_cores/processor' = $processorcorecount;
    number_of_disks = $numberofdisks
}

#Add disk number and size to $vmwarefile hash
$i = 0
ForEach($d in $drives){
    $vmwarefile.Add('Disk'+$i++, $d)
} 

我无法让它循环并将Disk'+ $ i ++的结果添加为Key,将$ d添加为哈希值。 有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

$count=1
$h=@{}
ForEach($_ in $phydisks){
    $cylinders = $datafile["$_"]["Cylinders"]
    $head = $datafile["$_"]["TracksPerCylinder"]
    $sectors = $datafile["$_"]["SectorsPerTrack"]
    $bytespersector = $datafile["$_"]["BytesPerSector"]
    $physicaldrivegb = ((([int]$cylinders * [int]$head * [int]$sectors * [int]$bytespersector) /     1024) / 1024) /1024
    $physicaldrivesize = [math]::Round($physicaldrivegb,1)

    $h."Disk$($count)" =  $physicaldrivesize
    $count+=1   
}
$h