Issue
What I need today? I just need to create a simple PowerCLI script to clone a VM, after it has been powered off.
Solution
Disclaimer: Use it at your own risk.
The following script is used to create a clone of a specific VM (after it has been shut down).
Before running, replace the following fields with your information:
<VCENTER>: Source vCenter (where the VM is running)
<USERNAME>: Username to connect to the vCenter (whit right permition to clone)
<PASSWORD>: Password of the user
<DATASTORE_TARGET>: Datastore target where. to place the cloned VM
Below the script:
############################################## # LM: Use it at your own risk # Clone a VM on the specific Datastore and attach the suffix "_Clone" to the VM Name (cloned) ############################################## if ($args[0].length -gt 0) { $vmName = $args[0] } else { Write-Host -ForegroundColor red "Usage: .\CloneVM.ps1 <VM_Name>" exit 40 } Connect-VIServer -Server <VCENTER> -User <USERNAME> -Password <PASSWORD> $vm = Get-VM -Name $vmName if ((Get-VM -Name $vmName).PowerState -eq "PoweredOff") { Write-Host -foreground Green "- VM "$vmName "is already OFF" } else { Write-Host -foreground Red "- VM "$vmName "is shutting down ..." $vm | Shutdown-VMGuest -Confirm:$false While ((Get-VM -Name $vmName).PowerState -ne "PoweredOff") { Write-Host -foreground yellow "... waiting for" $vmName "to power off" sleep 5 } } $ds = Get-Datastore -Name <DATASTORE_TARGET> $esx = Get-Cluster -VM $vmName | Get-VMHost | Get-Random $vm = New-VM -VM $vmName -Name $vmName'_CLONE' -Datastore $ds -VMHost $esx Set-VM $vmName -name $vmName'_Clone' -confirm:$false Disconnect-VIServer -Server * -Force -Confirm:$false
That's it.