PowerCLI Tips

Here is a new blog post based on the information provided, with a minimum word count of 500:

Cloning a Powered Off VM in PowerCLI

=====================================

As a PowerCLI enthusiast, I often find myself needing to clone a virtual machine (VM) that has been powered off. While there are several ways to accomplish this task, one of the most straightforward methods is to use the `New-VM` cmdlet in conjunction with the `Get-VM` and `Shutdown-VMGuest` cmdlets. In this blog post, we will explore how to clone a powered off VM using PowerCLI.

Disclaimer: Use it at your own risk.

Before we dive into the script, it’s important to note that you should replace the following fields with your own information:

* “: Source vCenter (where the VM is running)

* “: Username to connect to the vCenter (with right permissions to clone)

* “: Password of the user

* “: Datastore target where to place the cloned VM

Script

——

The script below is used to create a clone of a specific VM (after it has been shut down). Before running, replace the fields mentioned above with your own information. Here’s 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 “

exit 40

}

Connect-VIServer -Server -User -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

$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! With this script, you can easily clone a powered off VM in PowerCLI. Just remember to replace the fields with your own information before running the script.

As always, be careful when using this script, as it can potentially cause data loss or other issues if not used correctly.