In an ESXi environment, managing virtual machines (VMs) via SSH can be a powerful way to automate tasks and streamline administration. In this guide, we'll walk through the process of listing VMs, checking their power state, powering them on, gracefully shutting down their guest OS, and finally powering them off using command-line tools.

VMWare commands

Listing VMs

This command provides a list of VMs along with their IDs, making it easy to identify the VMs we want to manage.
vim-cmd vmsvc/getallvms

Getting Power State

This command returns whether the VM is powered on, off, suspended, etc., allowing us to determine its current state before taking further action.
vim-cmd vmsvc/power.getstate VMID

Powering On a VM

This command initiates the boot process for the VM, allowing its guest OS to start up
vim-cmd vmsvc/power.on VMID

Shutting Down a VM

This command sends a shutdown signal to the VM, allowing its guest OS to perform a clean shutdown before the VM powers off.
vim-cmd vmsvc/power.shutdown VMID

Powering Off a VM

This command immediately powers off the VM without waiting for its guest OS to shut down
vim-cmd vmsvc/power.off VMID.

Script to simplify powering on/off VMs

I've created a simple but handy bash script called vms-power-state.sh that simplifies VM management via the command line.

Download

You can download it in Github

Overview

The script offers several commands to interact with VMs:

  • vms-power-state.sh Prints help text, providing an overview of available commands.
  • vms-power-state.sh list Displays a list of VMs along with their powering states.
  • vms-power-state.sh <poweron|shutdown|poweroff> <VM_NAME|ALL>:
    • poweron Powers on the specified VM or all VMs.
    • shutdown Initiates a graceful shutdown of the guest OS of the specified VM or all VMs.
    • poweroff Immediately powers off the specified VM.

Usage Examples

Let's walk through some usage examples of the script:

  • Listing VMs and Powering States:
    Running vms-power-state.sh list provides a clear overview of all VMs and their current powering states, making it easy to identify which VMs are powered on or off.
  • Powering On a VM:
    To power on a VM, simply run vms-power-state.sh on <VM_NAME|ALL>.
  • Gracefully Shutting Down a VM:
    To initiate a graceful shutdown to perform a clean shutdown of a VM's guest OS, use vms-power-state.sh shutdown <VM_NAME|ALL>.
  • Powering Off a VM:
    To power off immediately a VM, use vms-power-state.sh shutdown <VM_NAME>.

Whether you need to power on/off VMs or gracefully shut down their guest OS, this script provides a convenient way to perform these tasks directly from the command line.