$Name is defined only within the foreach. You can't use it outside.
To customize the network, you have two possibilities.
-- The simple one
Enter for every VM the appropriate command into the script (Set-NetworkAdapter and Set-VMGuestNetworkInterface) => Just copy/paste and adjust the ip addresses.
This will get very unhandy with increasing VM count.
-- The complex one
Adjust the $newVmList to an array, with a hash table for each vm containing the network data, and loop through (same as you did before).
With this method, you also could provide the VM data from a csv file or an other source.
But you should get used with hash tables, otherwise it could be confusing.
Windows PowerShell Tip: Working with Hash Tables
$newVmList = @( @{"Name" = "SRV01"; "IP" = "192.168.1.100"; "Netmask" = "255.255.255.0"; "Gateway" = "192.168.1.1"; "DNS" = @("192.168.1.2", "192.168.1.3"); "NetworkName" = "VM2"; }, @{"Name" = "SRV02"; "IP" = "192.168.1.101"; "Netmask" = "255.255.255.0"; "Gateway" = "192.168.1.1"; "DNS" = @("192.168.1.2", "192.168.1.3"); "NetworkName" = "VM2"; }, @{"Name" = "SRV03"; "IP" = "192.168.1.102"; "Netmask" = "255.255.255.0"; "Gateway" = "192.168.1.1"; "DNS" = @("192.168.1.2", "192.168.1.3"); "NetworkName" = "VM2"; }, @{"Name" = "SRV04"; "IP" = "192.168.1.103"; "Netmask" = "255.255.255.0"; "Gateway" = "192.168.1.1"; "DNS" = @("192.168.1.2", "192.168.1.3"); "NetworkName" = "VM2"; } )
Then you have to make a small change to the New-VM foreach. Should then look like this
foreach($VM in $newVmList) { $taskTab[(New-VM -Name $VM.Name -VMHost (Get-VMHost -Name $esxName) -Template $template -Datastore $datastore -OSCustomizationSpec $custSpec -Location $location -RunAsync).Id] = $VM.Name }
After the Start-Sleep -Seconds 300, you could loop through the $newVmList again to customize the network for each VM.
foreach($VM in $newVmList) { Get-NetworkAdapter -VM $VM.Name | Set-NetworkAdapter -NetworkName $VM.NetworkName -Confirm:$false Get-VM -Name $VM.Name | Get-VMGuestNetworkInterface -Guestuser "Administrator" -GuestPassword "MYPASSWORD" | ? { $_.name -eq "Local Area Connection 3" } | Set-VMGuestNetworkInterface -Guestuser "Administrator" -GuestPassword "MYPASSWORD" -IPPolicy static -IP $VM.IP -Netmask $VM.Netmask -Gateway $VM.Gateway -DNS $VM.DNS }
Regards
Emanuel