Search code examples
powershellpowercli

Use 2 arrays in one loop


I want to use 2 arrays in one loop, but I am failing each time to find out how?

$hosts = "1.1.1.1,2.2.2.2,3.3.3.3"
$vmotionIPs = "1.2.3.4,5.6.7.8,7.8.9.0"
foreach ($host in $hosts) ($vmotionIP in $vmotionIPs)
  New-VMHostNetworkAdapter -VMHost $host-VirtualSwitch myvSwitch `
    -PortGroup VMotion -IP $vmotionIP -SubnetMask 255.255.255.0 `
    -VMotionEnabled $true

I know the above syntax is wrong but I just hope it conveys my goal here.


Solution

  • The most straightforward way is to use a hashtable:

    $hosts = @{
        "1.1.1.1" = "1.2.3.4" # Here 1.1.1.1 is the name and 1.2.3.4 is the value
        "2.2.2.2" = "5.6.7.8"
        "3.3.3.3" = "7.8.9.0"
    }
    
    # Now we can iterate the hashtable using GetEnumerator() method.
    foreach ($hostaddr in $hosts.GetEnumerator()) { # $host is a reserved name
        New-VMHostNetworkAdapter -VMHost $hostaddr.Name -VirtualSwitch myvSwitch `
            -PortGroup VMotion -IP $$hostaddr.Value -SubnetMask 255.255.255.0 `
            -VMotionEnabled $true
    }