VirtualBox – Power Off A Lot of VMs

While working on the OpenStack Cookbook (buy it here), we used Vagrant (check it out here). Vagrant allowed us to specify a number of VMs in a given file, and power them all up or down as a single operation. It was extremely useful for sharing an environment between two authors.

That said, there are times where I was stupid, and deleted the working directory before powering things off. So Vagrant wouldn’t know where they were. That’s where some bash-fu came in handy.

Listing Running VirtualBox VMs

To list running VirtualBox VMs as a user, do the following:

$ vboxmanage list runningvms
"OpenStackCookbook_proxy_1383150151" {e442cd01-b54d-412b-9fd4-42908f19b654}
"OpenStackCookbook_controller_1383150393" {366946e7-072b-4ff0-9bf5-d0d27446fc83}
"OpenStackCookbook_network_1383150946" {546b8836-ea88-4db7-b888-4a14227b21f6}
"OpenStackCookbook_compute_1383151216" {f5a1a331-54a7-4e9b-9db6-bc70f577a154}
"OpenStackCookbook_cinder_1383151629" {2781ed56-dfaa-49e9-9bfe-618d1f930412}

Powering Off All Running VirtualBox VMs

To power off all of said VMs, this can be done:

$ for i in `vboxmanage list runningvms | awk '{print $1}' 
| sed 's/"//g'`; do vboxmanage controlvm $i poweroff; done
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

What this command does, in a one liner is:

  • Get a list of all running VM Names
    • List all Running Vms – vboxmanage list runningvms
    • Grab the first bit of that output – awk ‘{print $1}’
    • Strip the quotes so we have good names – sed ‘s/”//g’
  • Loop over that list, passing each name to the power off command:
    • for i in
    • vboxmanage controlvm $i poweroff

Summary

In this post we showed you how to list all running VirtualBox VMs on a system and then power them off.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.