Script to shutdown VMs in a VMware cluster

Shut down all the powered on vms in a cluster

I came across this issue earlier in the week.  While completing some maintenance work on the virtual infrastructure, I needed to find a way of powering down all the vms I had in one of my VMware clusters.  Whatever the reason, it’s always nice to have a script handy to manage this for you.  So, here is a script to make things a little easier.  In this example I have 2 clusters that contain a number of vms in each and these clusters relate to different site locations – this will all depend on how you have your site set up.

Requirements

You will need the VMware Powershell module ‘vmware.vimautomation.core‘.  You will also need to load up the module and connect to your VI servers.  In my case I have 2, one for each site – so the following lines are added into my profile.ps1 file located in ‘C:\Windows\System32\WindowsPowerShell\v1.0’

Below is the script broken down into sections

Start by getting a list of all your VMware clusters and initialising your location vms strings:

Get a list of all the powered on vms in each cluster and output the information into a local text file (I do this so I have a record of what was powered on before I started).  As you can see from the code below I am omitting any vm with the name “*mgmt*” – This is so I can keep the management server online to be shut down last (I will need the ESX host IP address of this system later to be able to start it)

Functions

I have created functions to power down the vms and power up the vms, based on the contents of the 2 locationvms.txt files created above.  The function below can be called by typing ‘stoplocation1vms‘ from the Powershell command line once the script has been run.  Below I use a do-while loop to run through until all the systems have been powered down.  Don’t forget that your management server will be excluded if you changed the section above ($_.Name -notlike “*mgt*”) to coincide with your server naming convention.  I am also give each server 15 seconds, so as to not put too much a load on the ESX hosts.

The function below will start up your vms, also while not putting too great a load on your ESX hosts.  The function below can be called by typing ‘startlocation1vms‘ from the Powershell command line once the script has been run.  Don’t forget that you will need your management server up first before you can run this function.  This is why I created the local text files with all the vm that were in a powered on state before I started.

Leave a Reply

Your email address will not be published. Required fields are marked *