VMware Cloud Community
jvm2016
Hot Shot
Hot Shot
Jump to solution

hash_table with nested foreach loop_powercli

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

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

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

Reply
0 Kudos
4 Replies
jterli
VMware Employee
VMware Employee
Jump to solution

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 

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

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

Reply
0 Kudos
jvm2016
Hot Shot
Hot Shot
Jump to solution

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

}

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

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

Reply
0 Kudos