Spartacus75
Contributor
Contributor

How to pass parameters in a variable in a loop FOREACH ?

Hello everyone

I opened a new topic because I need your lights.

I have a script that allows me to automatically create multiple virtual machines.

I would now like to put parameters into a variable so that I can from select from my command prompt the number of machines at create and the name of machines.

I tried the variable args [] but it does not work in a foreach loop.

Here my script:

Connect-VIServer -Server 10.*.*.* -Protocol https -User admin-Password admin

2..$args[0] | Foreach {
New-vm -vmhost Server1.rio.paris.eu -Name "$args[1]$_" -Template TestScript -Datastore Database_1

}

2..$args[0] | Foreach {
Start-VM -VM "$args[1]$_"
}

In this script, the variable "$args[0]" to indicate the number of machine created and  the variable "args[1]" to indicate the name of the machines.

But it does not work.

I hope to have been clear on my problem.

Thanks so much for your help.

0 Kudos
22 Replies
LucD
Leadership
Leadership

There is a <CR><LF> missing it seems.

The lines should look like this

$vm = Get-VM $Name$_
while ($vm.PowerState -ne PoweredOn){   sleep 5
  $vm = Get-VM $vm
}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
Spartacus75
Contributor
Contributor

Hello LUCD,

Thank you for your availability.

Yes I actually put the code as follows:

"

$vm = Get-VM "$Name$_" 
while ($vm.PowerState -ne "PoweredOn"){   sleep 5
  $vm = Get-VM $vm
}"

But it does not work, I get the following error: "Get-VM: Can not validate argument on parameter 'Name'. Argument is null The gold empty."

The code is there in the right place in the script ?

Thanks you.

0 Kudos
LucD
Leadership
Leadership

Those lines should be in a foreach loop, like the earlier code in the script.

Then the $_ variable will hold the number to be added to the basename.

2..$Count | Foreach {
  $vm = Get-VM "$Name$_"
  while ($vm.PowerState -ne "PoweredOn"){
    sleep 5
    $vm = Get-VM $vm
  }
}

This will wait for all VM to be powered on.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos