Cloning Hyper-V VMs with PowerShell

Unlike when using Windows Admin Center to manage your Hyper-V VMs, Hyper-V Manager, nor the built-in cmdlets, offer any native VM cloning function. But with a bit of creative scripting, it's certainly doable. Here is a script that clones a virtual machine in Hyper-V:

# Script to clone a VM in Hyper-V
# Author: Johan Arwidmark
# Twitter: @jarwidmark
# LinkedIn: https://www.linkedin.com/in/jarwidmark

$SourceVMName = "PC0001"
$CloneVMName = "PC0001-CLONE"
$ExportFolder = "E:\Export"
$CloneFolder = "F:\VMs\$CloneVMName"

If (Test-Path $CloneFolder){
    Write-Warning "Clone folder: $CloneFolder already exists. Aborting script..."
    Break
}

# Export the Source VM
Export-VM $SourceVMName -Path $ExportFolder

# Import the Exported VM, full copy, and generating a new ID
$CloneVMConfigFile = (Get-ChildItem "$ExportFolder\$SourceVMName" -Filter *.vmcx -Recurse | Select -First 1).Fullname

$CloneVMConfig = @{
    Path = $CloneVMConfigFile;
    SnapshotFilePath = Join-Path $CloneFolder "Snapshots";
    VhdDestinationPath = Join-Path $CloneFolder "Virtual Hard Disks";
    VirtualMachinePath = $CloneFolder;
}

$Result = Import-VM -Copy -GenerateNewID @CloneVMConfig 

# Rename the imported VM (will be imported with original name)
$Result | Rename-VM -NewName $CloneVMName

# Remove the exported VM
$SourceVMExportPath = "$ExportFolder\$SourceVMName"
If (Test-Path $SourceVMExportPath) { Remove-Item -Path $SourceVMExportPath -Recurse -Force }
About the author

Johan Arwidmark

2 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

>