VMware Cloud Community
snandy
Contributor
Contributor

Clone selected drive only - Ignore listed Disk

I need to clone a VM ignoring certain disks while doing this.

Below is the code I have currently thanks to @DougBear

https://communities.vmware.com/t5/VMware-PowerCLI-Discussions/Clone-selected-drive-only-Ignore-Independent-Disk/td-p/2177953
$sourceVMname = "999_999TEST8AP"
$targetVMname = "999_999TEST8AP_Clone_PRJ_29032022"
$targetLocation = Get-Folder -Name "Infra" | % {Get-View $_.ID}
$DiskToExclude = @("Hard disk 8","Hard disk 2")

$vm = Get-VM $sourceVMname
$vmmor = $vm | Get-View



# Get device key for the hard disk
foreach($dev in $vmmor.Config.Hardware.Device){
foreach($disk in $DiskToExclude){

if ($dev.DeviceInfo.Label -ne $disk){
continue
} else {
#Define the clone specification
$vmclonespec = New-Object VMware.Vim.VirtualMachineCloneSpec
#Get information about the hard disk device
$vmclonespec.config = New-Object VMware.Vim.VirtualMachineConfigSpec
## Define what to change in the cloned VM's Configuration
$vmclonespec.config.deviceChange = @()
$vmclonespec.config.deviceChange += New-Object VMware.Vim.VirtualDeviceConfigSpec
$vmclonespec.config.deviceChange[0].device = New-Object VMware.Vim.VirtualDevice
$vmclonespec.config.deviceChange[0].device.key = $dev.Key
$vmclonespec.config.deviceChange[0].device.unitnumber = $dev.UnitNumber
$vmclonespec.config.deviceChange[0].operation = "remove"

$vmclonespec.location = New-Object VMware.Vim.VirtualMachineRelocateSpec
$vmclonespec.powerOn = $false
$vmclonespec.template = $false

$vmmor.CloneVM_Task($targetLocation.MoRef, $targetVMname, $vmclonespec )
}
}
}

but when I am executing the code, it is starting two tasks and giving below error,

Please let me know what is wrong here

Labels (2)
Reply
0 Kudos
7 Replies
LucD
Leadership
Leadership

There are several issues.
- you are calling the method inside the loop, in other words for each vDisk
- you can't clone the type of disks mentioned in the error message


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
snandy
Contributor
Contributor

@LucD Agree with your first point. tested without this but then also got the same error.

for your second point, then what can be done?

 

Reply
0 Kudos
LucD
Leadership
Leadership

You have to exclude independent disks and RDM disks.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
snandy
Contributor
Contributor

@LucD Yes. only independent

DiskMode is  "independent_persistent"

Reply
0 Kudos
LucD
Leadership
Leadership

And the clone method can not handle that type of disks.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
snandy
Contributor
Contributor

@LucD Then how should I approach the solution?

Reply
0 Kudos
LucD
Leadership
Leadership

Exclude independent disks


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos