Chapter 11
Backing Up and Restoring Your Virtual Machines

In this chapter, you will learn to:

  • Work with Snapshots
  • Create Do-It-Yourself Backups
  • Restore Your VMs from a DIY Backup
  • Change Block Tracking
  • Checking CBT Status
  • Enabling/Disabling CBT
  • Provide PowerShell Support for Corporate Backup Applications
  • Dell
  • Veeam

One of the most critical areas of any infrastructure—whether or not it is virtual—is backup, the replication of key data to an alternate location in case of data or hardware loss. Most organizations have a full backup strategy with complex replication scenarios and standby hardware on separate sites in case a disaster strikes. Other aspects of backup protect the system administrator and the users of the virtual infrastructure and its VMs from more day-to-day data loss or operating system corruption. This chapter will show you how you can use PowerCLI in both of these areas to help back up your VMs and also how you can use a PowerShell-enabled product from a third-party vendor to automate your backup tasks.

Work with Snapshots

Using VMware snapshots can be a great way to enable a quick and easy method to return to a particular point in time without needing to restore backups. A snapshot captures the state of a virtual machine and its configuration. Snapshots are a powerful tool for the VMware administrator as, once created, they act as a safety net ensuring any changes to the VM can be reverted if necessary. They are a restore point and should be created prior to installing new software, patching operating systems, or even making configuration changes. If you are unfamiliar with creating, maintaining, and restricting the creation of snapshots, see Chapter 9, “Advanced Virtual Machine Features.”

Create Do-It-Yourself Backups

Many organizations employ complex, commercially available products for creating backups. But what if you wanted to perform your own backups? Perhaps you want to copy your VM offsite to another datacenter—set, ready, and waiting to protect you in the event of disaster. Perhaps you just want to make a copy of the VM or VMs on a scheduled basis to ensure that your data has a backup.

With the code in Listing 11-1, you can make a backup copy of your VMs to an alternate datastore. The script creates a snapshot of the VM and then, from this snapshot, it clones the information to create a new VM on an alternate datastore. The script can be used to back up one or more VMs. As written, the log currently outputs to screen, but you can just as easily write to a log file or email the details as they are completed.

Listing 11-1: DIY backups

function Backup-VM {
<#
.SYNOPSIS
Backs up a virtual machine to a specified datastore.
.DESCRIPTION
The function will back up a virtual machine to a given datastore.
.PARAMETER VM
The Virtual Machine to back up
.PARAMETER  Datastore
The datastore to use when creating the backup VM
.INPUTS
String
System.Management.Automation.PSObject.
.OUTPUTS
VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl
.EXAMPLE
Backup-VM -VM Server01 -Datastore "NFS11"
.EXAMPLE
Get-VM Test01,Test02 | Backup-VM -Datastore (Get-Datastore "NFS11")
#>
[CmdletBinding(SupportsShouldProcess,ConfirmImpact="High")]`
 [OutputType('VMware.VimAutomation.ViCore.Impl.V1.Inventory.`
 VirtualMachineImpl')]

    Param
    (

    [parameter(Mandatory=$true,ValueFromPipeline=$true,`
     ValueFromPipelinebyPropertyName=$true)]
    [ValidateNotNullOrEmpty()]
    [PSObject[]]$VM,

    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [PSObject]$Datastore
    )

    begin {

        # --- Set Date format for clone names
        $Date = Get-Date -Format "yyyyMMdd"

        # --- Check the Datastore type
        if ($Datastore.GetType().Name -eq "string"){

            try {
                $Datastore = Get-Datastore $Datastore -ErrorAction Stop
            }
            catch [Exception]{
                throw "Datastore $Datastore does not exist"
            }
        }

        elseif ($Datastore -isnot [VMware.VimAutomation.ViCore.Impl.V1.`
         DatastoreManagement.NasDatastoreImpl] -or $Datastore -isnot `
         [VMware.VimAutomation.ViCore.Impl.V1.DatastoreManagement.`
          VmfsDatastoreImpl]){
            throw "You did not pass a string or a Datastore object"
            }
    }

    process{
        try {

        foreach ($CurrentVM in $VM) {

        if ($CurrentVM.GetType().Name -eq "string"){

            try {
                $CurrentVM = Get-VM $CurrentVM -ErrorAction Stop
            }
            catch [Exception]{
                Write-Warning "VM $CurrentVM does not exist"
                continue
            }
        }

        elseif ($CurrentVM -isnot [VMware.VimAutomation.ViCore.Impl.V1.`
         Inventory.VirtualMachineImpl]){
            Write-Warning "You did not pass a string or a VM object"
            continue
        }

        Write-Verbose "$($CurrentVM.Name) Backing up"
        Write-Verbose "$($CurrentVM.Name) Creating Snapshot"

        if ($PSCmdlet.ShouldProcess($CurrentVM)){

        # --- Create new snapshot for clone
        $CloneSnap = $CurrentVM | New-Snapshot -Name "Snapshot created on`
          $Date by backup script"

        # --- Get managed object view

        $VMView = $CurrentVM | Get-View -Property Parent,Snapshot

        # --- Get folder managed object reference
        $CloneFolder = $VMView.Parent

        $CloneVM = "BAK-$CurrentVM-$Date"

        Write-Verbose "$($CurrentVM.Name) Cloning from snapshot to `
        $CloneVM"

        # --- Build clone specification
        $CloneSpec = New-Object Vmware.Vim.VirtualMachineCloneSpec
        $CloneSpec.Snapshot = $VMView.Snapshot.CurrentSnapshot

        # --- Make linked disk specification
        $CloneSpec.Location = New-Object Vmware.Vim.VirtualMachineRelocateSpec
        $CloneSpec.Location.Datastore = $Datastore.Id
        $CloneSpec.Location.Transform = `
        [Vmware.Vim.VirtualMachineRelocateTransformation]::flat

        # --- Create clone
        $CreateClone = $VMView.CloneVM($CloneFolder, $CloneVM, $CloneSpec)

        Write-Verbose "$($CurrentVM.Name) Clone created"
        Write-Verbose "$($CurrentVM.Name) Removing Snapshot"

        # --- Remove Snapshot created for clone
        Get-Snapshot -VM (Get-VM -Name $CurrentVM) -Name $CloneSnap |
          Remove-Snapshot -confirm:$False
        Write-Verbose "$($CurrentVM.Name) Backup completed"

        # --- Output the VM object
        $OutputVM = Get-VM $CloneVM
        Write-Output $OutputVM
        }
    }
}
     catch [Exception] {

           throw "Unable to back up VM $($CurrentVM.Name)"
     }



    }

    end {

    }
}

This function will perform the backup to the datastore provided, but you need to keep a few things in mind:

  • The amount of disk space needed for the backup will be exactly the same as the current virtual machine’s disks.
  • No de-duplication methods were applied to this backup. Third-party software could have made use of de-duplication, in which case the amount of data being stored would be significantly reduced.
  • The backup file will be a complete copy of the virtual machine, which means if you were to power it on you would have an exact replica on the network, conflicting IP addresses, SID, and all!
  • The script will not work if the VM has raw device mappings (RDMs) or independent disks.

In the next section, you will learn how to change the VM network settings en masse to help you double-check that your backups have completed successfully and that you have a working VM.

Restore Your VMs from a DIY Backup

Having backed up your virtual machines using the code in Listing 11-1, you obviously will want to restore them at some point, even if it is just to verify a successful backup. At other times, you will want to use this technique to automate a move to an isolated network so that you can verify that a virtual machine boots correctly into a working state. This is a great way to ensure the data you are backing up is the data you need and not a corrupted VM.

We named the backup VMs we created earlier in Listing 11-1 with a naming convention that added the prefix BAK- to the VM name. Now, you can easily specify these backed-up VMs and perform various recovery actions on them. Here’s how.

To ensure that the backup VMs will not conflict with the original VMs, you can use the following script and change the network to a preconfigured isolated network (Listing 11-2).

Listing 11-2: Setting the VM network to an isolated network

Get-VM BAK-* | Get-NetworkAdapter | `
Set-NetworkAdapter -NetworkName "Isolated Network" -Confirm:$false

The simple code in Listing 11-2 allows you to be safe in the knowledge that the virtual machines are now in an isolated network—away from your production network. While in the isolated network, they can be powered on and checked for a confirmed, good restore; be used to restore individual files; or even be used to replicate a live environment for testing purposes.

Change Block Tracking

One of the feature enhancements introduced back in vSphere 4 was the ability to enable Changed Block Tracking (CBT). CBT is often described in the same way as differential backups. Initially, you copy all data from source to target. This first copy (often called a seed) is a full copy of the data. With CBT enabled, when you go to copy the data the next time you copy only data that has been changed since the last backup. ESXi will track the block changes that have taken place since a given point in time. Before this feature was available on vSphere, both host CPU and memory resources had to be used to compare the versions of data and establish the changes that needed to be backed up. With this feature implemented, ESXi tracks the changes by keeping a log of all blocks that have been modified; it does not keep a copy of the changed blocks themselves. Overall, this makes the backup of your virtual machines much quicker. ESXi is able to examine the log and tell your backup application exactly what has changed since the last backup, thereby reducing the amount of data being transferred.

Before CBT can be used, the following must be completed:

  • Your ESX hosts will need to be on ESXi 4 at least.
  • Your VMs will need to be updated to hardware version 7.

Checking CBT Status

As mentioned earlier, before CBT can be used, each VM must have been upgraded to hardware version 7 and CBT must have been enabled. You can check both of these requirements using the script in Listing 11-3.

Listing 11-3: CBT prerequisites

New-VIProperty -Name CBTEnabled -ObjectType VirtualMachine `
  -ValueFromExtensionProperty 'Config.ChangeTrackingEnabled' `
  -Force

Get-VM VM01 | Select Name, Version, CBTEnabled

Enabling/Disabling CBT

Currently, no native cmdlet exists that enables or disables CBT for your VMs. But we’ve got your back. We wrote an advanced function (Listing 11-4) that you can use to enable or disable CBT on either a single VM or multiple VMs.

Listing 11-4: Enabling and disabling CBT

function Set-VMCBT {
<#
.SYNOPSIS
Enables and Disables CBT for a VM or multiple VMs
.DESCRIPTION
The function will enable and disable CBT for a VM
or multiple VMs
.PARAMETER VM
A virtual machine or multiple virtual machines
.PARAMETER Enabled
Specify if CBT should be enabled with $true
or disabled with $false
.INPUTS
String
System.Management.Automation.PSObject.
.OUTPUTS
VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl
.EXAMPLE
Set-VMCBT -VM VM01 -Enabled $true
.EXAMPLE
Get-VM VM01,VM02 | Set-VMCBT -Enabled $false
#>

 [CmdletBinding(SupportsShouldProcess,ConfirmImpact="High")]`
 [OutputType('Selected.VMware.VimAutomation.ViCore.Impl.V1.`
  Inventory.VirtualMachineImpl')]

    Param
    (
    [parameter(Mandatory=$true,ValueFromPipeline=$true,`
     ValueFromPipelinebyPropertyName=$true)]
    [ValidateNotNullOrEmpty()]
    [PSObject[]]$VM,

    [parameter(Mandatory=$false)]
    [ValidateNotNullOrEmpty()]
    [Bool]$Enabled
    )

    begin {
    }

    process{
        try {

        foreach ($CurrentVM in $VM) {

        if ($CurrentVM.GetType().Name -eq "string"){

            try {
                $CurrentVM = Get-VM $CurrentVM -ErrorAction Stop
            }
            catch [Exception]{
                Write-Warning "VM $CurrentVM does not exist"
                continue
            }
        }

        elseif ($CurrentVM -isnot [VMware.VimAutomation.ViCore.Impl.V1.`
         Inventory.VirtualMachineImpl]){
            Write-Warning "You did not pass a string or a VM object"
            continue
        }

        # --- Create the config spec
        $VMView = $CurrentVM | Get-View -Property Name
        $VMConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec

        if ($Enabled) {

            Write-Verbose "Enabling CBT for $($CurrentVM.Name)"
            $VMConfigSpec.changeTrackingEnabled = $true
        }
        else {

            Write-Verbose "Disabling CBT for $($CurrentVM.Name)"
            $VMConfigSpec.changeTrackingEnabled = $false
        }
        if ($PSCmdlet.ShouldProcess($CurrentVM)){
        # --- Make the CBT change
        $VMView.ReconfigVM($VMConfigSpec)

        # --- Create the output object
        $CurrentVM = Get-VM $CurrentVM | Select Name,
@{N='CBTEnabled';E={$_.ExtensionData.Config.ChangeTrackingEnabled}}
        Write-Output $CurrentVM
        }
        }

        }
        catch [Exception]{

           throw "Unable to set CBT on VM $($CurrentVM.Name)"
        }
    }

    end {

    }
}

Provide PowerShell Support for Corporate Backup Applications

There are obvious reasons to use a corporate backup application. These dedicated applications have great features that enable better data compression, de-duplicate, and provide scheduling advantages. Packages have often been purchased as part of a strategic corporate backup plan and are used for both physical and virtual environments, for backing up to multiple locations, and for verifying the consistency of data.

Recently, backup vendors have been adding PowerShell support to their packages. (By now you should realize that PowerShell is a great and easy way to add automation to any product. It makes sense that backup software vendors have come to that realization, too.)

Think about how long it would take you to

  • Add multiple backup jobs for multiple servers
  • Change the backup schedule for multiple servers
  • Extract information for multiple servers
  • Remove a backup job for multiple servers

If you have a corporate backup application, we suggest that you check it now to see what you can achieve by using PowerShell. The remaining sections of this chapter present two such applications and discuss the kind of things you can achieve with PowerShell in a commercial backup environment.

Dell

Dell has a PowerShell-enabled backup product called vRanger. vRanger has a variety of backup methods and a good compression algorithm to ensure that the size of backups and the time it takes to back them up is greatly reduced. vRanger has its own Active Block Mapping feature, which reads only active blocks from the image, similar to VMware’s CBT, as discussed earlier in this chapter. With vRanger, you can back up and restore VMs at the same time. Leveraging distributed processing avoids impact on host operations and sends VM data through a single, central server.

vRanger also has great vCenter Server integration, allowing it to see which VMs have been protected, when backup jobs are completed, and which VMs still need backup protection. You can configure new backup jobs that are automatically refreshed to stay current with new VMs as they are added to the virtual environment.

vRanger was one of the first backup products to include PowerShell cmdlets to allow you to manage every aspect of the product, ensuring automation at all levels of the virtual infrastructure. As of version 7.1.1 there are 100 cmdlets available within the vRanger PowerShell Snap-in.

Requirements

The vRanger PowerShell Snap-in is included as part of a default installation of version 7.1.1 of vRangerBackup & Replication.

Getting Started

Since the vRanger cmdlets are part of a PowerShell Snap-in, you can add them to your PowerShell session using the Add-PSSnapin cmdlet (Listing 11-5). Alternatively, a default install of vRanger places a vRanger Console icon in the Dell folder of the Windows Start Menu. Choosing this will open a PowerShell session with the vRanger cmdlets already loaded.

Listing 11-5: Adding the vRanger Snap-in to a PowerShell session

Add-PSSnapin vRanger.API.PowerShell

Before you can start creating any backup jobs, you first must connect vRanger to a source of servers. The product is capable of backing up VMs from VMware vCenter and Microsoft Hyper-V, as well as physical machines, and contains cmdlets for connecting to each of these source types. We will focus on the VMware vCenter source.

Connecting vRanger to vCenter

As part of connecting vRanger to vCenter, you will need a set of credentials to establish the connection and have permission to back up the intended virtual machines. It is good practice to use a dedicated service account for this purpose and grant the account the permissions in vCenter that it will require. Then, use the Add-VirtualCenter cmdlet (Listing 11-6) to make the connection.

Listing 11-6: Connecting vRanger to vCenter

$vCenterCredentials = Get-Credential
Add-VirtualCenter -DNSorIP vcenter01.sunnydale.local -Username `
  $vCenterCredentials.UserName -UserPassword `
  ($vCenterCredentials.GetNetworkCredential()).Password

Create a Repository

You need a repository as a target for your backup jobs to store the backup data. vRanger 7.1.1 supports the following target types: Windows Share (CIFS), SFTP, FTP, NFS , NetVault SmartDisk (NVSD), EMC Data Domain Boost (DDB), and Dell Rapid Data Access (RDA). There are separate cmdlets for creating each type of repository. In Listing 11-7, we create an NFS repository to use as our backup job target.

Listing 11-7: Creating an NFS repository

Add-NfsRepository -Name SynologyNFS -Server synology.sunnydale.local `
  -ExportDirectory 'volume8/vRanger' -TargetDirectory Backups

Retrieve an Entity from the Source Inventory

Another requirement for a backup job is to identify the VMs you wish to include as part of the backup. vRanger allows you to supply these as any of a number of vCenter objects: a vCenter Cluster, Datacenter, Folder, ResourcePool, Virtual Center, ESXi Host, or a specific list of VMs. An advantage of using a vCenter object such as a Cluster or Folder rather than a specific list of VMs is that when the VMs contained within those objects change, there is no need to amend the backup job.

You can use the Get-InventoryEntity cmdlet to list the possibilities. Listing 11-8 demonstrates how to retrieve all VMs, specific VMs, all clusters, and a specific cluster. No filtering can be done at the cmdlet level, so the standard PowerShell cmdlet Where-Object must be used to filter the results appropriately. When it is time to create the backup job, use Get-InventoryEntity to supply the VMs or vCenter object to include.

Listing 11-8: Retrieving VMs and clusters as entities from the source inventory

Get-InventoryEntity -Type VirtualMachine
Get-InventoryEntity -Type VirtualMachine |
  Where-Object {$_.Name -eq 'Server01'}

Get-InventoryEntity -Type ClusterComputeResource
Get-InventoryEntity -Type ClusterComputeResource |
  Where-Object {$_.Name -eq 'Cluster01'}

Schedule

For our example backup job, we also need to create the schedule for when the job will run. The vRanger Snap-in provides five cmdlets for creating a schedule depending on your requirements: New-DailySchedule, New-IntervalSchedule, New-MonthlySchedule, New-WeeklySchedule, and New-YearlySchedule. Listing 11-9 demonstrates how to create a schedule for Monday–Friday, inclusive, starting at 8 p.m.

Listing 11-9: Creating a Monday–Friday schedule

$Schedule = New-WeeklySchedule -ExecutionDays `
  'Monday,Tuesday,Wednesday,Thursday,Friday' -StartTime 20:00

Backup Job Template

You now have all of the elements in place required to create a backup job template. Listing 11-10 creates a backup job for all VMs in the Cluster named Cluster01, stores the data in the SynologyNFS repository, and uses the schedule created in Listing 11-9. There are a multitude of other options for creating a backup job template; a few are used in Listing 11-10. However, it is well worth checking the help for Add-BackupJobTemplate to see what is available.

Listing 11-10: Creating a backup job template

$ClusterEntity = Get-InventoryEntity -Type ClusterComputeResource |
  Where-Object {$_.Name -eq 'Cluster01'}
$TargetRepository = Get-Repository -Type NFS |
  Where-Object {$_.Name -eq 'SynologyNFS'}
$Schedule = New-WeeklySchedule -ExecutionDays `
  'Monday,Tuesday,Wednesday,Thursday,Friday' -StartTime 20:00
Add-BackupJobTemplate -JobName Cluster01 -JobEntity $ClusterEntity `
  -TargetRepository $TargetRepository -JobSchedule $Schedule `
  -NumberOfSavePoints 5 -SpaceSavingTechnologyTypeFlag Differential `
  -Flags NoFlags

Multiple Backup Job Templates

Creating a single backup job template in PowerShell is not necessarily going to save a significant amount of time over creating one in the vRanger GUI. However, when you turn to creating multiple backup job templates, that’s when the time savings can be seen. Listing 11-11 demonstrates how to create a backup job template for clusters 01–05 that staggers the start time for each cluster by one hour. Notice that it was not a significant uplift in the code required from creating a single backup job template.

Listing 11-11: Creating multiple backup job templates

$Clusters = 'Cluster01','Cluster02','Cluster03','Cluster04','Cluster05'
$TargetRepository = Get-Repository -Type NFS |
  Where-Object {$_.Name -eq 'SynologyNFS'}
$InitalStartTime = [DateTime]"20:00"
$i = 0

foreach ($Cluster in $Clusters){

    $ClusterEntity = Get-InventoryEntity -Type ClusterComputeResource |
      Where-Object {$_.Name -eq $Cluster}
    $BackupTime = $InitalStartTime.AddHours($i)
    $i++

    $Schedule = New-WeeklySchedule -ExecutionDays `
      'Monday,Tuesday,Wednesday,Thursday,Friday' -StartTime $BackupTime
    Add-BackupJobTemplate -JobName $Cluster -JobEntity $ClusterEntity `
      -TargetRepository $TargetRepository -JobSchedule $Schedule `
      -NumberOfSavePoints 5 -SpaceSavingTechnologyTypeFlag Differential `
      -Flags NoFlags
}

Restore Job Template

To restore a VM from a backup job with vRanger, you need to create a restore job template. This can be done via the Add-RestoreJobTemplate cmdlet. The key part of creating a restore job template is identifying the Savepoint to use. Every time a vRanger backup job is run, a Savepoint is created for each VM, and depending on the backup job template configuration, it is possible to store multiple numbers of Savepoints per VM. So for a restore job template, you need to identify the Savepoint—first by VM and then by time.

Listing 11-12 creates a restore job template for a VM named Server01 that uses the most recent Savepoint for that VM in the SynologyNFS repository and does not overwrite the existing Server01 VM, but rather creates a VM with a new name—an exercise, for example, you might go through to test the validity of a backup. Using the -RunJobNow parameter, you kick off an immediate restore. As with Add-BackupJobTemplate, it is well worth checking the help for Add-RestoreJobTemplate; there are a multitude of possible options that can be used to configure a restore job template.

Listing 11-12: Creating a restore job template

$Repository = Get-Repository -Type NFS |
  Where-Object {$_.Name -eq 'SynologyNFS'}
$RestoreSavepoint = Get-RepositorySavePoint $Repository.id |
  Where-Object {$_.VMName -eq 'Server01'} | Sort-Object StartTime |
  Select-Object -Last 1
Add-RestoreJobTemplate -Jobname Restore01 -Savepoint $RestoreSavepoint `
  -VMName Server01_Restore -RunJobNow $true

Veeam

Veeam is a vendor best known for their backup and replication software for virtual machines. By leveraging the virtual environment and Veeam vPower technology, Veeam always seems to be on the forefront of backup technologies, introducing new and innovative ways to not only back up the virtual environment but also restore. They have several methods that ensure each of the backups created can be 100 percent guaranteed to restore. With Veeam Backup & Replication (VBR) you can instantly recover a VM directly from a backup file, restore individual objects (email messages, database records, files, etc.) from any virtualized application or filesystem, verify the recoverability of every backup, and provide near-continuous data protection for any application.

Veeam was also one of the first vendors to add PowerShell support to their application. As of version 8.0, they have 272 cmdlets that can be used to manage this application.

Requirements

Ensure that you select Veeam Backup & Replication PowerShell SDK during the installation procedure since it is not a default option in version 8.0.

Getting Started

Since the VBR cmdlets are part of a PowerShell Snap-in, we can add them to our PowerShell session using the Add-PSSnapin cmdlet (Listing 11-13).

Listing 11-13: Adding the Veeam Snap-in to a PowerShell session

Add-PSSnapin VeeamPSSnapIn

Before you can start creating any backup jobs, you need to connect VBR to a source of servers. The product is capable of backing up VMs from VMware vCenter, VMware vCloud Director, and Microsoft Hyper-V, and contains cmdlets for connecting to each of these source types. We will focus on the VMware vCenter source.

Connecting Veeam Backup & Replication to vCenter

As part of connecting VBR to vCenter, you will need a set of credentials to establish the connection and have permission to back up the intended virtual machines. It is good practice to use a dedicated service account for this purpose and grant the account the permissions in vCenter that it will require. Then use the Add-VirtualCenter cmdlet to make the connection (Listing 11-14).

Listing 11-14: Connecting VBR to vCenter

$vCenterCredentials = Get-Credential
Add-VBRvCenter -Name vcenter01.sunnydale.local -User `
  $vCenterCredentials.UserName -Password `
  ($vCenterCredentials.GetNetworkCredential()).Password

Create a Repository

You will need a repository as a target for our backup jobs for backup data storage. VBR 8.0 supports the following target types: Microsoft Windows Server, Linux Server, CIFS/SMB file share, EMC Data Domain, ExaGrid, and HP StoreOnce. The Add-VBRBackupRepository cmdlet is used to create a VBR repository. In Listing 11-15, we create an SMB repository to use as our backup job target.

Listing 11-15: Creating an SMB Repository

$SMBCredentials = Get-Credential
Add-VBRBackupRepository -Name 'SynologySMB' -Folder `
  '\synology.sunnydale.localvbr' -Type CifsShare -UserName `
  $SMBCredentials.UserName -Password `
  ($SMBCredentials.GetNetworkCredential()).Password

Retrieve an Entity from the Source Inventory

Another requirement for a backup job will be to identify the VMs you wish to include as part of the backup. VBR allows you to supply these as a number of vCenter objects: a vCenter Cluster, Datacenter, Folder, ResourcePool, Virtual Center, ESXi Host, or a specific list of VMs. An advantage of using a vCenter object such as a Cluster or Folder rather than a specific list of VMs is that when the VMs contained within those objects change, there is no need to amend the backup job.

You can use the Find-VBRViEntity cmdlet to list out the possibilities. Listing 11-16 demonstrates how to retrieve a specific VM and a specific cluster. Filtering can be applied using the -Name parameter. When it is time to create the backup job, we will use Find-VBRViEntity to supply the VMs or vCenter object to include.

Listing 11-16: Retrieving VMs and clusters as entities from the source Inventory

Find-VBRViEntity -Name Server01 -VMsAndTemplates
Find-VBRViEntity -Name Cluster01 -ResourcePools

Schedule

For each backup job, you also need a schedule for when the job will run. The VBR Snap-in provides the Set-VBRJobSchedule cmdlet for setting the schedule for a job after it has been created.

Backup Job Template

You now have all of the elements in place required to create a backup job template. Listing 11-17 creates a backup job for all VMs in the cluster named Cluster01, will store the data in the SynologySMB repository, and use a schedule of weekdays starting at 8 p.m. There are a multitude of other options for creating backup job templates, so it is well worth checking the help for Add-VBRVIBackupJob, Set-VBRJobOptions, and Set-VBRJobSchedule to see what is available.

Listing 11-17: Creating a backup job template

$ClusterEntity = Find-VBRViEntity -Name Cluster01 -ResourcePools
$Repository = Get-VBRBackupRepository -Name SynologySMB
Add-VBRViBackupJob -Name Cluster01 -Entity $ClusterEntity `
  -BackupRepository $Repository

$Job = Get-VBRJob -Name Cluster01
$Job | Set-VBRJobSchedule -DailyKind WeekDays -At "20:00"
$JobOptions = Get-VBRJobOptions -Job $Job
$JobOptions.JobOptions.RunManually = $false
Set-VBRJobOptions -Job $Job -Options $JobOptions

Multiple Backup Job Templates

Creating a single backup job template in PowerShell is not necessarily going to save you a significant amount of time over creating one in the VBR GUI. However, when you turn to creating multiple backup job templates that’s when the time savings can be seen. Listing 11-18 demonstrates how to create a backup job template for clusters 01–05 and stagger the start time for each cluster by one hour. Notice that it was not a significant uplift in the code required from creating a single backup job template.

Listing 11-18: Creating multiple backup job templates

$Clusters = 1..5 | ForEach-Object {"Cluster0$_"}
$Repository = Get-VBRBackupRepository -Name SynologySMB
$InitalStartTime = [DateTime]"20:00"
$i = 0

foreach ($Cluster in $Clusters){

    $ClusterEntity = Find-VBRViEntity -Name $Cluster -ResourcePools
    Add-VBRViBackupJob -Name $Cluster -Entity $ClusterEntity `
      -BackupRepository $Repository

    $BackupTime = $InitalStartTime.AddHours($i)
    $i++

    $Job = Get-VBRJob -Name $Cluster
    $Job | Set-VBRJobSchedule -DailyKind WeekDays -At $BackupTime
    $JobOptions = Get-VBRJobOptions -Job $Job
    $JobOptions.JobOptions.RunManually = $false
    Set-VBRJobOptions -Job $Job -Options $JobOptions

}

Restore Job

To restore a VM from a backup job with VBR, you need to use the Start-VBRRestoreVM cmdlet. The key to using this cmdlet is identifying the Restorepoint. Every time a VBR backup job is run, a Restorepoint is created for each VM and, depending on the backup job template configuration, it is possible to store multiple numbers of Restorepoints per VM. So to restore a VM, you need to identify the Restorepoint—first by VM name and then by time. You also need to specify an ESXi host to restore the VM to. This can be found using the Get-VBRServer cmdlet.

Listing 11-19 starts a restore job for a VM named Server01 using the most recent Restorepoint for that VM in the SynologySMB repository. It does not overwrite the existing Server01 VM, but creates a VM with a new name. A specific ESXi host is used via Get-VBRServer for the restored data.

Listing 11-19: Restoring a VM

$RestoreSavepoint = Get-VBRRestorePoint -Name Server01 |
  Sort-Object CreationTime | Select-Object -Last 1
$Server = Get-VBRServer -Name "pesxi01.sunnydale.local"
Start-VBRRestoreVM –RestorePoint $RestoreSavepoint -VMName `
  Server01_Restore -Server $Server -RunAsync
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset