In part 2, I shared the PowerCLI scripting I used to power on my entire lab environment in the correct order. In this final installment, I’ll take you through the scripting used to power everything down. Although you may think the process is just the reverse of what I covered in part 2, you’ll see there were some other things to consider and different approaches required.
Step 1 – Shutting Down Compute Cluster VMs
To begin the process, I’d need to shut down all VMs in the compute-a cluster. None of the VMs there are essential for running the lab, so they can be safely stopped at any time. I was able to do this by connecting to vCenter with PowerCLI and then using a ‘foreach’ loop to gracefully shut down any VMs in the ‘Powered On’ state.
"Connecting to vCenter Server ..." |timestamp Connect-VIServer -Server 172.16.1.15 -User administrator@vsphere.local -Password "VMware9(" "Shutting down all VMs in compute-a ..." |timestamp $vmlista = Get-VM -Location compute-a | where{$_.PowerState -eq 'PoweredOn'} foreach ($vm in $vmlista) { Shutdown-VMGuest -VM $vm -Confirm:$false | Format-List -Property VM, State }
The above scripting ensures the VMs start shutting down, but it doesn’t tell me that they completed the process. After this is run, it’s likely that one or more VMs may still be online. Before I can proceed, I need to check that they’re all are in a ‘Powered Off’ state.
"Waiting for all VMs in compute-a to shut down ..." |timestamp do { "The following VM(s) are still powered on:"|timestamp $pendingvmsa = (Get-VM -Location compute-a | where{$_.PowerState -eq 'PoweredOn'}) $pendingvmsa | Format-List -Property Name, PowerState sleep 1 } until($pendingvmsa -eq $null) "All VMs in compute-a are powered off ..."|timestamp
A ‘do until’ loop does the trick here. I simply populate the list of all powered on VMs into the $pendingvmsa variable and print that list. After a one second delay, the loop continues until the $pendingvmsa variable is null. When it’s null, I know all of the VMs are powered off and I can safely continue.