Justin Rich

VM datastore clone testing using Powershell

Discussion created by Justin Rich on Jun 27, 2013

been working with VM datastore cloning and running syspreps so i've made a couple of scripts, first one is to run a customization template on all VMs on the new datastore and the other is to remove those VMs and remove the DS

 

The cleanup uses a Nimble PowerShell module I created

jrich523/NimblePowerShell · GitHub

 

This will import all the VMs and rename and sysprep them. there are some assumptions on the template name and how i want the new names to be

 

$vmhost = "hostname"

$networkname = "network adapter name"

$dsname = "CloneTest2" ##whatever you named your new clone

$instance = "Dev3" ## Im cloning for development env, this and the next two var's are just for how we build computer names

$id = "D3"

$Prefix = "TUK"

 

#get all VMX (vm's) on the datastore

$vmxs = gci vmstore:\$((Get-Datacenter).name)\$dsname -Recurse -Include *.vmx | select -exp datastorefullpath

 

foreach($vmx in $vmxs)

{

    $currentname = ($vmx -split "/|\.")[1]

    $name = "$Prefix$ID$currentname"

    $currentVM = get-vm $currentname

    #$os is used to pick the customization template

    $os = if($currentVM.Guest.OSFullName -match "(20\d\d)"){$matches[1]}else{Write-Error "cant find OS version" -ea Stop}

   

    #set location

    $vm = new-vm -Name $name -VMFilePath $vmx -VMHost $VMhost -ea Stop

   

    Set-VM -VM $vm -OSCustomizationSpec "$os-NP-Dev" -Confirm:$false -ea Stop

    Get-NetworkAdapter -VM $vm | Set-NetworkAdapter -NetworkName $networkname -StartConnected $true -Confirm:$false  -ea stop

    # the start will toss a question error but i cant answer the question until i attempt to start it...

    Start-VM $vm

    Get-VMQuestion -VM $vm | Set-VMQuestion -DefaultOption -Confirm:$false

}

 

 

once the test is complete and I want to clean up, I run this, which relies on the module. Im going to look in to using the module to do the cloning as well to hopefully get a VSS consistent snap

 

 

$dsname = "CloneTest2"  ##clone name

$arrayIP = "192.168.1.10"

$password = "arraypassword"

 

Get-VM -Datastore $dsname | stop-vm -Confirm:$false -ea 0 | Remove-VM -Confirm:$false  ## remove all VMs on DS from inventory

sleep 2

Remove-Datastore $dsname -Confirm:$false -VMHost $vmhost

Connect-NSArray -SystemName $arrayIP -Password $password

Remove-NSVolume -Name CloneTest2 -Force

Remove-NSSnapShot -Name CloneTest2 -Volume CloneTest -Force

Get-VMHost | Get-VMHostStorage -RescanAllHba -RescanVmfs

 

 

 

any suggestions/input/question would be great

Outcomes