Search This Blog

Friday, September 9, 2011

Automated Script to re-register VM

There's a bug in vSphere 4.* that requires your to re-register/reregister  (remove then re-add) before you can edit the VM. VMware has a workaround (http://kb.vmware.com/kb/1025367), so here's the PowerCLI code that makes it easier:

param ($VM, [switch]$WhatIf=$False, [switch]$RunAsync = $False)
#script to re-register a vm

process{

     if ($_){
          $VM = $_
     }

     if (( $VM | GM)[0].TypeName -match "VirtualMachineImpl|TemplateImpl"){

          foreach ($v in $vm){

               if (( $v | GM)[0].TypeName -match "TemplateImpl"){
                    $v = $v | Set-Template -ToVM -confirm:0
                    $RunAsync = $False
               }

               $VMFilePath = $v | Get-View | % { $_.Config.Files.VmPathName } 
               #$vuid =  $v | % { $_.Uid.Split("/")[1] }

               if ( ( $VMFilePath ) -and ($v.VMHost.ConnectionState -eq "Connected") ){

               $zn = Remove-VM -vm $v -DeletePermanently:0 -whatif:$whatif -confirm:0  
               New-VM -Name $v.name -WhatIF:$whatif -VMHost $v.vmhost -VMFilePath $VMFilePath -Location $v.Folder   -RunAsync:$RunAsync

               }elseIf ($v.VMHost.ConnectionState -ne "Connected" ){
                    write-host -foreground red -background white $v.name on $v.VMhost is $v.VMhost.ConnectionState

               }
          }

     }else{ 
          write-host -fore Yellow "-VM Not VIrtualMachineImpl" 
     }
}

No comments:

Post a Comment