900-poweroff-vm
#!/bin/bash
#
# Safe Power-down VM and wait until VM is powered down
# If ACPI is not on, can do a hard powerdown as well
#
# Run user check
if [ "$UID" -eq 0 ]
  then echo "This script should NOT be run as root."
  exit 1
fi
#
if [[ ! ("$#" == 1) ]]; then
  echo "Usage for $0 : VM Name required as argument."
  exit 1
fi
VB_VM_NAME=$1
# The ITERA and SLEEP parameters determine polling duration and interval
#   to check if the VM has been powered down
VM_POWER_DOWN_ITERA=30
VM_POWER_DOWN_SLEEP=2
# Setting Force to 1 will Shutdown VM through Hard powerdown if ACPI is off
VM_FORCE_POWER_DOWN=0
#
# Power-off VM if running
VM_POWERED_ON=`VBoxManage list runningvms|grep -c '^"'${VB_VM_NAME}'"'`
if [ $VM_POWERED_ON -eq 1 ]; then
  echo "VM $VB_VM_NAME is up. Powering down VM."
  VM_ACPI_SW=`VBoxManage showvminfo ${VB_VM_NAME}|grep ACPI|grep -c on`
  if [ $VM_ACPI_SW -eq 1 ]; then
    VBoxManage controlvm ${VB_VM_NAME} acpipowerbutton
  else
    if [ $VM_FORCE_POWER_DOWN -eq 0 ]; then
      echo "ACPI is off on VM. Unable to safely powerdown from Host"
      exit 1
    else
      echo "ACPI is off on VM. Hard powerdown of VM!"
      VBoxManage controlvm ${VB_VM_NAME} poweroff
    fi
  fi
else
  echo "VM $VB_VM_NAME is already Powered down or does not exist"
  exit 0
fi
COUNTER=1
until [ $VM_POWERED_ON -lt 1 ]; do
    sleep $VM_POWER_DOWN_SLEEP
    VM_POWERED_ON=`VBoxManage list runningvms|grep -c '^"'${VB_VM_NAME}'"'`
    echo "Waiting $VM_POWER_DOWN_SLEEP additional seconds for VM to power down."
    echo " - Iteration ${COUNTER}/${VM_POWER_DOWN_ITERA} ..."
    let COUNTER+=1
    if [ $COUNTER -gt $VM_POWER_DOWN_ITERA ]; then
        echo "VM does not seem to be powering down!"
        echo "Exiting ..."
        exit 1
    fi
done
if [ $COUNTER -gt 1 ]; then
    echo "VM Powered down in approximately $(echo "${VM_POWER_DOWN_SLEEP}*${COUNTER}" | bc) seconds."
fi
#
exit