create a hashtable with foreach

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of CTX_Christian CTX_Christian 2 years, 1 month ago.

  • Author
    Posts
  • #19947
    Profile photo of CTX_Christian
    CTX_Christian
    Participant

    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

  • #19949
    Profile photo of Simon Wåhlin
    Simon Wåhlin
    Participant

    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.

  • #19950
    Profile photo of CTX_Christian
    CTX_Christian
    Participant

    Thanks Simon! That worked.

    I will checkout the PSCustomObjects subject now.

    Thanks again.

    Regards

    Christian

You must be logged in to reply to this topic.