Last active
March 30, 2024 09:38
-
-
Save phyoewaipaing/aac626b314a7bf7e46c0c41ba8b4c8b4 to your computer and use it in GitHub Desktop.
Script that will set all esxi hosts into maintenace mode if no VMs are left running
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## This script will put the evacuated esxi hosts into maintenance mode if no VMs are running, checked every X seconds for Y duration ## | |
## $Script_Runtime_in_Minutes : Duration (in minutes) the script will be running | |
## $Wait_Time_in_Second_for_Next_Check : Duration (in seconds) to wait for the next check of vmhosts | |
## $VMhost_Name_Criteria : This filters the VMhost to be included according the given regular expression eg: ^192.168.0 to include all the esxi hosts starting with 192.168.0 or leave it blank ("") if you want to include all esxi hosts | |
## Author : Phyoe Wai Paing | |
## Date : 15.July.2021 | |
## Version : 1.0 : Initial Release | |
$Script_Runtime_in_Minutes = 30; ## Y duration described in above comment section | |
$Wait_Time_in_Second_for_Next_Check = 15; ## X duration described in above comment section | |
$VMhost_Name_Criteria = "" ## Leave it blank or define it in regular expression to include specific exsi hosts (described in above comment section) | |
$NumberOfLoops = $Script_Runtime_in_Minutes * 60 / $Wait_Time_in_Second_for_Next_Check | |
for ($i=0;$i -lt $NumberOfLoops; $i++) | |
{ | |
write-host "`nTime: $((get-date).ToString('hh:mm:ss'))`n-------------------------------------------------"; | |
Get-vmhost | ?{ $_.name -match $VMhost_Name_Criteria } | % { | |
$NumRunVMs = ($_ | get-vm | ? {$_.Powerstate -eq "PoweredOn"}).Count; | |
If ($NumRunVMs) | |
{ write-host "Host: $($_.Name) Running VMs: $NumRunVMs" } | |
else | |
{ | |
$HostConnectionState = (Get-VMhost -Name $($_.Name)).ConnectionState | |
If ($HostConnectionState -eq "Maintenance" ) | |
{ | |
write-host -fore Cyan "Host is already in maintenance mode: $($_.Name)" | |
} | |
elseif ($HostConnectionState -eq "Connected") | |
{ | |
write-host -fore green "Host will enter maintenance mode now: $($_.Name)" | |
Set-vmhost -VMhost $($_.Name) -State Maintenance | out-null; | |
} | |
else { | |
write-host -fore red "Host is in unknown state: $($_.Name)" | |
} | |
} | |
}; | |
start-sleep -Second $Wait_Time_in_Second_for_Next_Check; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment