Skip to content

Instantly share code, notes, and snippets.

@benkulbertis
Last active January 26, 2021 20:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkulbertis/7831068 to your computer and use it in GitHub Desktop.
Save benkulbertis/7831068 to your computer and use it in GitHub Desktop.
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 http://stackoverflow.com/a/203116
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.
echo Waiting for the VM to power down...
echo Please power down manually if the shutdown did not initiate.
) else goto BACKUP
:CHECK
:: 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
:BACKUP
:: Compact/optimize the image for smallest backup size
echo.
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.
echo Initiating backup now!
VBoxManage.exe export "%vmname%" --output "%bakroot%\%vmname%\%mydate%.ova"
:: Alert that the backup is complete
echo.
set /p=Backup complete! Press enter to close this window.
:END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment