With the help of crontab the script will search VM state every 1 hour to check if the VM’s are powered on or not.

— Putty to ESXi host
— Create a shell script (power-on.sh) which needs to be placed on a vmfs datastore and then copy paste the below script

vmname=”vm1″
vmid=$(vim-cmd vmsvc/getallvms | grep “$vmname” | awk ‘{print $1}’)
stat1=$(vim-cmd vmsvc/power.getstate “$vmid” | grep “off”)
if [ “$stat1” == “Powered off” ]
then
vim-cmd vmsvc/power.on “$vmid”
fi

— Replace ‘vm1’ with the appropriate VM name
— Save the file and give the executable permission

chmod 755 /vmfs/volumes/lun1/power-on.sh

— Create a cron job to execute this script every one hour

  1. Edit /var/spool/cron/crontabs/root using VI.
  2. Add the line (all on one line) at the bottom and save (:wq!).
    0 */5 * * * /vmfs/volumes/lun1/power-on.sh
  3. Run the command “cat /var/run/crond.pid
  4. That will print the process number of the running crond, such as 12345
  5. Run the command “kill 12345”

Note: Above Changes will not the persistent across the ESXi reboot

Add commands to /etc/rc.local.d/local.sh to re-generate the cron job when ESXi host reboots

  1. Edit /etc/rc.local.d/local.sh using a command such as “vi /etc/rc.local.d/local.sh“.
  2. At the end of the file just above ‘exit 0’, add following 3 lines. The first kills crond, the second adds the new cron job to the root crontab file, and the third restarts crond:

/bin/kill $(cat /var/run/crond.pid)
/bin/echo ‘0 */5 * * * /vmfs/volumes/lun1/power-on.sh’ >> /var/spool/cron/crontabs/root
crond

  1. Save and exit the file
  2. Run the command “auto-backup.sh” so that the change to /etc/rc.local.d/local.sh survives a reboot.
Advertisement