This is a quick blog post on rebooting ESXi hosts in a cluster by migrating VMs off the hosts, putting the host into maintenance mode, rebooting the hosts, checking host is up, then removing the host from maintenance mode and looping through the same process again for all the hosts in the given cluster. There are many scenarios this task can be handy for example keeping up with regular reboot cycle on a scheduled task, adding or removing storage from the hosts, changing a setting for all hosts in the cluster, applying driver settings etc.…
This loops through all hosts in the cluster and below is the script block
Param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string[]]$Cluster)
$ClusterName = "*$Cluster*"
## Start-Transcript
Start-Transcript -Path C:\Temp\hostreboot-transcript.txt
## Set Connection String
$cred = Get-Credential
$vCenters = "lab-vc01.lab.local", "lab-vc02.lab.local"
Connect-VIServer -Server $vCenters -Credential $cred
## Set Parameters
## Param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string[]]$Cluster)
## Param([Parameter(Mandatory=$true)][String]$Cluster)
Get-Cluster $ClusterName
if((Get-Cluster $ClusterName).count -gt 1)
{
Write-Host "Please Specify Less Than 1 Cluster"
## if the cluster name specified matches more than 1 cluster, the operation will be aborted
exit
}
else {
write host "$ClusterName is not more than 1 Cluster"
}
## Grab host lists and save in txt file - make sure you have enough permission to write into dir
(Get-Cluster $ClusterName |Get-VMHost).Name | Out-File C:\lab\LabHostReboot.txt
cd c:\lab\
Get-Content .\LabHostReboot.txt | %{
$Server = $_;
Write-Host -ForegroundColor Green "$Server"
Write-Host -ForegroundColor Yellow "`tServer Is Entering Maintenance Mode"
Set-VMHost $Server -State maintenance -Evacuate | Out-Null
Write-Host -ForegroundColor Yellow -NoNewline "`tServer is Rebooting"
Restart-VMHost $Server -Confirm:$false | Out-Null
## Wait 5 mins from reboot to check connection state of the Host
do {
sleep 2
$ServerState = (Get-VMHost $Server).ConnectionState
Write-Host -ForegroundColor Yellow -NoNewline "."
} while ($ServerState -ne "NotResponding")
Write-Host -ForegroundColor Yellow -NoNewline "(Server is powered down)"
## Another 5 mins wait post reboot to make sure server is up and in MM
do {
sleep 2
$ServerState = (Get-VMHost $Server).ConnectionState
Write-Host -ForegroundColor Yellow -NoNewline "`."
} while ($ServerState -ne "Maintenance")
Write-Host -ForegroundColor Yellow "(Server is Powered Up)"
## Set connection state to connected post reboot
Write-Host -ForegroundColor Yellow "`tServer Exiting Maintenance Mode"
Set-VMHost $Server -State Connected | Out-Null
Write-Host -ForegroundColor Yellow "`tHost Reboot Cycle Done!"
Write-Host ""
}
Stop-Transcript
Good script. Was looking to do this very thing this morning and this is exactly what I was trying to do.
I am glad you found it useful. Enjoy and share the love to the community