Use array values in a foreach loop

Christian van Eickelen 1 Reputation point
2021-04-05T20:54:41.173+00:00

Hello guys,

i'm trying to automate some VMware ESXi configurations via PowerShell using the VMware.PowerCLI module.

In my script define an array of ip addresses look like this:

$vMotionIps = @("192.168.0.1","192.168.0.2","192.168.0.3")

For the foreach i use this code:

$vmHosts = Get-VMHost
$vMotionIps = @("192.168.0.1","192.168.0.2","192.168.0.3")

foreach ($vmhost in $vmHosts)
{
$vss= Get-VirtualSwitch -VMHost $vmHost -Name vSwitch0
New-VMHostNetworkAdapter -VMHost $vmHost -PortGroup vMotion -VirtualSwitch $vss -VMotionEnabled:$true -IP $vMotionIps -Subnetmask 255.255.255.0
}

The goal is to set one IP from the array for the parameter "-IP", but i got an error message saying "The specified method is not supported"

May i ask you for what's wrong?

Greetings
Chris

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,383 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Andreas Baumgarten 97,396 Reputation points MVP
    2021-04-05T21:14:37.61+00:00

    Hi @chrisslicious-os ,

    based on this website -IP accepts a string. But you are tyring to insert an array. This might be the isssue.
    https://vdc-repo.vmware.com/vmwb-repository/dcr-public/6fb85470-f6ca-4341-858d-12ffd94d975e/4bee17f3-579b-474e-b51c-898e38cc0abb/doc/New-VMHostNetworkAdapter.html

    Could please try to use only one IP for $vMotionIps to see if the script is working.

    If you would like to add all three vMotionIps it might be required to use a foreach loop.

    Not tested!

    $vmHosts = Get-VMHost
    $vMotionIps = @("192.168.0.1","192.168.0.2","192.168.0.3")
    
    foreach ($vmhost in $vmHosts)
        {
        $vss= Get-VirtualSwitch -VMHost $vmHost -Name vSwitch0
            foreach ($vMotionIp in $vMotionIps) {
                New-VMHostNetworkAdapter -VMHost $vmHost -PortGroup vMotion -VirtualSwitch $vss -VMotionEnabled:$true -IP $vMotionIp -Subnetmask 255.255.255.0
                }
        }
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments