PowerShell script: backup running VMware VMs… Kind of

My first PowerShell script, it checks for running vms using vmrun, suspends them, backs up a designated VM directory using robocopy, and powers back on the suspended VMs.

#script settings
$backupfrompath = "c:\vms"
$backuptopath = "d:\vmsbackup"
#set location of vmrun command, can't use $env:ProgramFiles because of 64 bit OS
$vmrun = "C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"

#get a list of currently running vms
$runningVMs = &$vmrun list | where-object {$_ -notlike "Total*"}

#loop through running vms and suspend them
Foreach ($guestSystem in $runningVMs) {if ($guestSystem.length -gt 0 ) {&$vmrun suspend $guestSystem soft}}

#backup vms folder using robocopy
$copycommand = "robocopy " + $backupfrompath +" " + $backuptopath +" /E /R:2 /W:10 /NP /LOG+:" +$backuptopath +"\robocopy.log"
invoke-expression $copycommand

#loop through suspended vms and resume them
Foreach ($guestSystem in $runningVMs) {if ($guestSystem.length -gt 0 ) {&$vmrun start $guestSystem}}

Notes:

  • When testing I noticed that a vm file was still in use on one occasion, possibly vmware still had a lock on it, so I set robocopy retries to 2 and wait to 10 seconds.
  • To allow PowerShell scripts to run on Windows 7 I had to run set-executionpolicy RemoteSigned in PowerShell.
  • I set up the backup in task scheduler using the following settings
    • program / script: powershell.exe
    • arguments: -NonInteractive -NoProfile -Command "&{C:\backup\vmbackup.ps1}"
    • My own user account with highest privileges (needed to suspend and restart start vm with vmrun), and do not store password checked. Had real problems with Error: Cannot connect to the virtual machine when the script running from task scheduler was trying to resume vms. In the End I changed the task to run under the administrators group, running with highest privileges. Don’t know if this is specific to my setup / Win 7 / Workstation 7.1.

Leave a Reply