0
votes

I'm running a simple cloning script that should clone the VMs, then replace the network adapters too. The issue is that cloning tasks start async, the network adapter change tasks start before the clone is done and (of course) fails to change them.

The script:

foreach($VM in $VMs){
    newVM = New-VM -Name $VM.name.replace($oldEnv,$newEnv) -VM $VM -DiskStorageFormat Thin -Datastore "DS" -ResourcePool "RP"
    $allNetworkAdapters = $newVM | Get-NetworkAdapter  
    Foreach ($OldNetworkAdapter in $allNetworkAdapters){
       $OldNetwork = $OldNetworkAdapter.NetworkName
       $NewNetwork = $OldNetwork.replace($oldEnv,$newEnv)
       $newVM | Get-NetworkAdapter | Where {$_.NetworkName -eq $OldNetwork } | Set-NetworkAdapter -NetworkName $NewNetwork -Confirm:$false
    }
}

Is there any way to start the cloning task and wait until it is done to continue with the next line in the script ?

Is this the exact code being used? I ask because New-VM isn't a server side task by default, but a task can be spawned anyways with a RunAsync parameter. However, doing so changes the output to the newVM variable, of which is missing the variable designation on the 2nd line.Kyle Ruddy