Using PowerShell to take Virtual Server snapshots… (Part Four)

This is my fourth and final posting in this series.  In this last posting I will be wrapping the backup script that we have been working on.  Most of this post will be code, so mind the formatting.

To start things off, we need to first un-pause all of the VMs that we previously paused.  We are doing this because we have already taken a snap-shot of all of the VMs.  There is no need to keep these VMs paused, as that would defeat the purpose of the script.

foreach ($Server in $Servers){    # We need to make sure to only un-pause the servers     # that we paused.    if($Server.Paused -eq "Yes"){       $VM = $MSVS.findVirtualMachine($Server.Name)       $Null = [Microsoft.VirtualServer.Interop.Powershell]::SetSecurity($VM)       # Now that we have the snapshot we can un-pause the VM.       $Progress = $VM.Startup()       $Null = `        [Microsoft.VirtualServer.Interop.Powershell]::SetSecurity($Progress)       # Again we display the progress of the action we are doing.       while ($Progress.PercentCompleted -lt 100){          write-progress -Activity "Starting - $($Server.Name)" `             -Status "Progress:" `             -PercentComplete ($Progress.PercentCompleted)             }         }      }

Next, we need to mount each of the snap-shots before we use Robocopy to copy the snap-shots to our backup location.

foreach ($Drive in $Drives){   $ID = $Drive.ID   $Path = join-path $ScriptPath $ID   $Null = mkdir $Path   $Null = .\Resources\vshadow.exe "-el=`{$ID`},$Path"      }

After mounting each snap-shot we now need to use Robocopy to copy them to the path defined in the $DestPath variable.  The following loop handles this for us:

foreach ($Server in $Servers){   # Just in case you want to have log file.   $LogFileName = ".\Logs\MSVSBackup_" + $Server.Name + ".log"   $BackupPath = join-path $DestPath $Server.Name   $ID = $Drive | where {$_.Drive -eq $Server.Drive} | select ID   $SourceStem = $Server.Path   $SourceStem = $SourceStem.subString(2, $SourceStem.length - 2)   $SourcePath = join-path $SourcePath $SourceStem   .\Resources\robocopy.exe $SourcePath $BackupPath /TEE /LOG:$LogFileName      }

   $SourcePath = join-path $ScriptPath $ID.ID 

Lastly, after the snap-shots have all been copied, we need to remove them.  The following bit of code does that:

foreach ($Drive in $Drives){   $ID = $Drive.ID   $Null = .\Resources\vshadow.exe "-ds=`{$ID`}"   remove-item $ID      }

Hopefully this series has been helpful.  Over time, I plan on posting more of my production scripts so that other can use them.  However, it sure would be nice if NetworkWorld would make posting source code a little easier.  Then I might be more inclined to post a little bit more.

Join the Network World communities on Facebook and LinkedIn to comment on topics that are top of mind.
Related:

Copyright © 2007 IDG Communications, Inc.

SD-WAN buyers guide: Key questions to ask vendors (and yourself)