Saturday, April 12, 2014

Shutdown virtual datacenter quickly using script

Warning: All the testings are performed in lab environment, use them at your own risk. This blog is created for knowledge purpose, I will not be responsible for any damage.

I found one question on the vmware community that if it is possible to create a script to graceful shutdown all vm's and Esxi hosts in the vCenter Server

So thought its worth a creating powercli script.


 #####################################  
 ## http://kunaludapi.blogspot.com  
 ## Version: 1  
 ## Tested this script on  
 ##  1) Powershell v3  
 ##  2) Powercli v5.5  
 ##  3) Vsphere 5.x  
 #####################################

Add-PSSnapin vmware.vimautomation.core  
   
 # vCenter username password  
 $vcenteruser = "domain\user"  
 $vcenterpasswd = "Password"  
   
 # esxi host usernamd password  
 $esxiuser = "root"  
 $esxipasswd = "password"  
   
 #add your vcenter hostname /  
 $vCenterServer = "vCenterserver"  
 $vCenterDatabase = "vCenterDatabase"  
   
 #connect vCenter Server  
 Connect-VIServer -Server $vCenterServer -User $vcenteruser -Password $vcenterpasswd  
   
 #Gracefull shutdown all vms except vCenterserver  
 Get-VM | Where-Object {$_.name -ne $vCenterServer -and $_.name -ne $vCenterDatabase} | Shutdown-VMGuest -Confirm:$false  
 Start-Sleep -s 300  
   
 #Shutdown all Hosts except the esxi where vCenterserver is running.  
 #Make sure Vcenter and its database are on same host.  
 Get-VMHost | Where-Object {$_.Name -ne (Get-VM $vCenterServer | Get-VMHost).Name} | Stop-VMHost -Confirm:$false -Force  
 $esxihost = (Get-VM $vCenterServer | Get-VMHost).Name  
 Disconnect-VIServer $vCenterServer -Confirm:$false  
   
 #Connect to esxi host where vCenter and its database is hosting  
 Connect-VIServer -Server $esxihost -User $esxiuser -Password $esxipasswd  
   
 #Shutdown vcenter and database server  
 Get-VM | Shutdown-VMGuest -Confirm:$false  
 Start-Sleep -s 300  
   
 #shutdown last remaing host.  
 Get-VMHost | Stop-VMHost -Confirm:$false -Force  
 Disconnect-VIServer $ -Confirm:$false  

Below screenshot tells you how it will shutdown your vmware virtual datacenter.


No comments: