Checking for and Setting Maintenance mode on an ESXi Host via PowerCLI

Say you have to do a configuration change on an ESXi host – you know you can script that stuff out and put your feet up while it does it’s thang… Buuut you’re unsure about whether the host is in maintenance mode… what if its not on maintenance mode? What if it screws it up! Well in this post I’ll cover how you can check for as well as set maintenance mode effectively via PowerCLI.

Checking whether ESXi host is in Maintenance mode

The Get-VMHost cmdlet get the connection state of the ESXi host as well whether its connected, disconnected or in maintenance mode.

$host = "esx_host1" 
#Use the fqdn of the host

if($host.ConnectionState -eq "Maintenance"){
	write-host "The host is in maintenance mode"
	#Your configuration change code can go here

Setting ESXi host to Maintenance mode

$host = "esx_host1" 
#Use the fqdn of the host

#Set host to maintenance mode
Get-VMHost -Name $hosts | set-vmhost -State Maintenance

	$host_info = Get-VMHost $hosts
	$count = $count + 1
	#check if 5 minutes had passed, if so exit 
	if ($count -gt 15){
		$failed = 1
		$msg = "Waiting for maintenance mode timed out. Please check the status from the vCenter"
		sleep 20
}until($host_info.ConnectionState -eq "Maintenance" )

This script issues the command to set the host to maintenance mode. Then checks every 20 seconds for 5 minutes whether the host is in maintenance mode. If not it will get a timeout error (say if one stubborn Virtual machine refuses to leave the host).