Highlighted
Hot Shot
Hot Shot

hash_table with nested foreach loop_powercli

Jump to solution

Hi Luc,

could you check folowing code .whats wrong in this though it works fine for one esxi host.

also does hash table has only one pair of key and value or can it be like key and mulitiplevalues.

$tab=@{}

foreach ($esxi in (get-cluster mycluster ))

{

foreach($scsil in (get-scsilun -vmhost $esxi))

{

$Tab[$scsil.canonicalname] = $scsil.multipathpolicy

0 Kudos
1 Solution

Accepted Solutions
Highlighted
User Moderator
User Moderator

Yes, that is correct.

But you are still assigning 1 value, in this case an array.

The notation $a,$b is an array object, where the array holds 2 elements.

In my earlier example is was assigning a hash table as the value, again 1 object


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
4 Replies
Highlighted
VMware Employee
VMware Employee

You can modify the code slightly as below

$tab=@{}

foreach ($esxi in (get-cluster mycluster | Get-VMHost))

{

foreach($scsil in (get-scsilun -vmhost $esxi))

{

$Tab[$scsil.canonicalname] = $scsil.multipathpolicy

}

The hash table can have a key with multiple key values 

0 Kudos
Highlighted
User Moderator
User Moderator

You forgot to loop over the ESXi nodes in the outer loop.
And a hash table entry can have only one key and one value, but the value part can be anything (a single value or a complex object).
You could do things like this for example

$tab=@{}

foreach ($esxi in (Get-Cluster -Name mycluster | Get-VMHost))

{

    foreach($scsil in (Get-ScsiLun -VmHost $esxi))

    {

        $Tab[$scsil.canonicalname] = @{

            MultiPathPolicy = $scsil.multipathpolicy

            VMHost = $esxi.Name

        }

    }

}

You would then address a specific property in a specific entry as follows

$tab['A_canonical_name'].VMHost


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
Highlighted
Hot Shot
Hot Shot

Hi Luc ,

thanks for correction .

just worked out following but since below works .does it not mean that hash table has multiple values .

so in below example canonical name as key   and multipathpolicy and capacityGB as two values. is this not correct?

$tab=@{}

$vmhosts=@("vmhost1","vmhost2")

foreach($esxi in $vmhosts)

{

$scsil=get-scsilun -vmhost $esxi

foreach ($sc in $scil)

{

$tab[$scsil.canonicalname] = $scsil.multipathpolicy,$scsil.capacityGB

}

0 Kudos
Highlighted
User Moderator
User Moderator

Yes, that is correct.

But you are still assigning 1 value, in this case an array.

The notation $a,$b is an array object, where the array holds 2 elements.

In my earlier example is was assigning a hash table as the value, again 1 object


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos