Skip to content

Instantly share code, notes, and snippets.

Last active January 26, 2021 20:30
What would you like to do?
This backs up my Ubuntu VM on my Windows work machine. It works with any Virtualbox VM by passing the VM name as an argument. I hate batch.
@echo off
:: This is the name (in Virtualbox) of the VM you want to back up. Pass it as an argument or change the '%1' below to the VM name.
set vmname=%1
set bakroot=D:\VM Backups
:: Get current date - from
for /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%a-%%b-%%c)
set /p start=The %vmname% VM is about to be backed up. Do you wish to continue (Y/[N])?
if /i "%start%" NEQ "Y" goto END
cd "\Program Files\Oracle\Virtualbox"
:: Initial check if the VM is running. If its not, skip straight to the backup. If it is, initiate shutdown and go to the "CHECK" loop below until it's down.
VBoxManage.exe showvminfo "%vmname%" --machinereadable 2>nul | find /i "poweroff" > nul 2>&1
if errorlevel 1 (
VBoxManage.exe controlvm "%vmname%" acpipowerbutton
echo Waiting for the VM to power down...
echo Please power down manually if the shutdown did not initiate.
) else goto BACKUP
:: Keep checking if the VM is off until it is
VBoxManage.exe showvminfo "%vmname%" --machinereadable 2>nul | find /i "poweroff" > nul 2>&1
if errorlevel 1 goto CHECK
:: Compact/optimize the image for smallest backup size
echo Compacting the virtual image for smallest backup size.
VBoxManage.exe modifyhd --compact "%UserProfile%\VirtualBox VMs\%vmname%\%vmname%.vdi"
:: Initiate backup via Virtualbox OVA export
echo Initiating backup now!
VBoxManage.exe export "%vmname%" --output "%bakroot%\%vmname%\%mydate%.ova"
:: Alert that the backup is complete
set /p=Backup complete! Press enter to close this window.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment