20 May 2011

Bulk unregister / register VMs on vSphere

If you want to unregister all VMs on a particular vSphere Cluster / Host you’re pretty done using the GUI, registering all VMs on a datastore could take you to the “hell of clicking masters” depending on the amount of VMs to register. I created two powershell functions which do that stuff for you.


unregisterallvm “datacenter-A” “Cluster-A10-LAB”
registerallvm “vcenter.domain.com” “datacenter-A” “Cluster-A10-LAB” “Datastore-SAN-001”
And here is the code for copy ‘n pasting:
Function unregisterallvm([STRING]$datacentername,[STRING]$clustername)
 $vms = Get-DataCenter $datacentername | Get-Cluster $clustername | get-vm
 Foreach ($vm in $vms)
   $vmname = $vm.name
   Write-Host "Unregistering VM: $vmname from Cluster $clustername"
   Remove-VM -VM $vmname -DeleteFromDisk:$false -Confirm:$false -RunAsync

Function registerallvm([STRING]$vCenterHost,[STRING]$datacentername,[STRING]$clustername,[STRING]$datastorename)
 $datastore = Get-Datacenter $datacentername | Get-Datastore | ? {$_.name -match $datastorename}
 $datastoreshortname = $datastore.Name
 $ResourcePool = Get-Cluster -Name $clustername | Get-ResourcePool | Get-View
 $vmFolder = Get-View (Get-Datacenter -Name $datacentername | Get-Folder -Name "vm").id
 $vmdirs = (dir "vmstores:\$vCenterHost@443\$datacentername\$datastoreshortname\")
 Foreach ($f in $vmdirs)
   $vmname = $f.Name
   $checkreg = (Get-Cluster $clustername | Get-VM | ? { $_.name -match $vmname})
   If (!$checkreg)
     "Registering VM: $vmname on: $clustername \ $datastoreshortname"
     $vmFolder.RegisterVM_Task("[$datastoreshortname]/$vmname/$vmname.vmx", $vmname, $false, $ResourcePool.MoRef, $null)   
     "VM: $vmname is already registered with the same name. Skipping...."

Of course you need to place this functions in your script before you’re calling them and you need PowerCLI snapin registered and have a connection to vCenter using:

connect-viserver -server "vcenter.domain.com"