For a scriptable control of Virtual Box machines we can make use of the
VBoxManage commands:
- List running machines (returns name and UUID):
VBoxManage list runningvms
- Stop running VMs by "hibernating" them (reommended to avoid data loss)
VBoxManage controlvm savestate
- Poweroff running VMs (not recommended because we may lose data in the guest)
VBoxManage controlvm poweroff
- Use ACPI in an ACPI-aware guest OS (preferable to
poweroff
for graceful shutdown of guests)
VBoxManage controlvm acpipowerbutton
Also see:
How to safely shutdown Guest OS in VirtualBox using command line
Update from OP
Based on this selected correct answer below, I've added this bash script "
$HOME/bin/stop-vagrant.sh
".
So now I have something that can safely begin a stop of all vagrant VMs
that I might have turned on yet forgotten about in a session.
vboxmanage list runningvms | sed -r 's/.*\{(.*)\}/\1/' | xargs -L1 -I {} VBoxManage controlvm {} savestate
Command Explained:
vboxmanage list runningvms |
-- gets a list of all running vms under VirtualBox
sed -r 's/.*\{(.*)\}/\1/' |
-- strips the string down to id number
xargs -L1 -I {} VBoxManage controlvm {} savestate
-- runs the save state command on each box that's open.
On
xargs
-L1
- take one line at a time
-I {}
- uses {} as a place holder for the next command