PoSH VirtualBox Shutdown All Running VMs

Note: This is a recovered post from my old blog. See how we recovered these posts using the Wayback Machine and AI tooling.

A script to gracefully shutdown all VirtualBox VMs before host shutdown. This is useful when you want to power down your host machine without manually closing each VM, the script sends an ACPI power button signal to each running VM, giving them time to shut down cleanly.

#Get running VMs and put into a list
$VMman = "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe"
$VMlist = & $VMman list runningvms
$VMnames = New-Object System.Collections.ArrayList
$VMnames.Clear()
#Remove UUID from VM list and create new array with just VM names.
foreach ($VMuuid in $VMlist){
$VMstring = $VMuuid.substring(0, $VMuuid.IndexOf('{'))
$VMname = $VMstring.Trim()
$VMnames.add($VMname)
}
#ACPI Shutdown each VM
foreach ($VM in $VMnames){
& $VMman controlvm $VM acpipowerbutton
Start-Sleep 5
}