create a hashtable with foreach

Hi NG,

I’m stuck currently with this simple task but I don’t understand what all the articles want to explain me.

I’m collecting a bunch of XenServer pool master IP addresses from XenDesktop. Then I want to loop through each of the IP addresses to get the corresponding hypervisorconnectionname. Sometime there can be more than 1 hypervisorconnectionnames for an IP address.

My issue is that the hash table only contains the last hypervisorname instead of all. What am I doing wrong here?

Get all Poolmaster IPs from XenDesktop broker

$poolmasterips = get-ChildItem xdhyp:\connections -AdminAddress $stradminaddress | select -ExpandProperty HypervisorAddress -Unique

foreach ($poolmasterip in $poolmasterips)
{

Get hypervisorconnection names from pool master IP

$hypervisorname = get-childitem xdhyp:\connections -AdminAddress $stradminaddress | where {$_.HypervisorAddress -eq $poolmasterip} | select -ExpandProperty HypervisorConnectionName

$hypervisornamelist = @{

name = $hypervisorname
}
}

Regards

Christian

Hi Christian,

You are overwriting the variable $hypervisorname in each iteration of your loop.

There are a few ways to solve this, the easiest in my opinion is to do this:

$Hypervisorlist = foreach ($poolmasterip in $poolmasterips)
{
   $hypervisorname = get-childitem xdhyp:\connections -AdminAddress $stradminaddress | where {$_.HypervisorAddress -eq $poolmasterip} | select -ExpandProperty HypervisorConnectionName
   @{
      name = $hypervisorname
   }
}

This will write the hash-table to the output stream, which will end up in the collection $Hypervisorlist

You might want to consider using PSCustomObjects instead of HashTables.

Thanks Simon! That worked.

I will checkout the PSCustomObjects subject now.

Thanks again.

Regards

Christian