Script Sample - VM Operations - Setting up the VM Backup

@20aman    Nov 23, 2018

If you want to set up VM Backup for multiple VMs in your environment you can leverage this script. This script lets you provide a CSV file as an input to the script and configures the Backup on all the VMs as per the configurations.

Script Requirements

The script requires you to populate the configurations CSV file. The sample CSV file is also provided along with the script. This configurations file should have the following columns:

  1. Computer - Name of the VM in Azure
  2. OSType - Windows or Linux
  3. ResourceGroupName - Resource Group of the VM
  4. EnableBackup - yes or no
  5. RecoveryServicesVaultName - Recovery Services Vault Name for the Backup
  6. BackupProtectionPolicy - Backup Protection Policy name inside the Recovery Services Vault. E.g. Daily-30--Weekly-8--Monthly-6

Script Working

The script first fetches the Azure Recovery Services vault using the below command.

$recoveryServicesVault = Get-AzureRmRecoveryServicesVault -Name $RecoveryServicesVaultName

It then uses this information to set the Recovery Services Vault Context as shown below.

$recoveryServicesVault | Set-AzureRmRecoveryServicesVaultContext -ErrorAction Stop

It then fetches the container for the VM Backup using below command. Through this, it checks if the Backup is already configured on the VM or not. If it is already configured then no further action is taken.

$namedContainerCheck = Get-AzureRmRecoveryServicesBackupContainer -ContainerType "AzureVM" -Status "Registered" -FriendlyName $virtualMachineName

The Backup policy is fetched next:

$policy = Get-AzureRmRecoveryServicesBackupProtectionPolicy -WorkloadType "AzureVM" | where {$_.Name -eq $BackupProtectionPolicy}

Finally, the Backup is configured on the VM using the below command.

Enable-AzureRmRecoveryServicesBackupProtection -Policy $policy -Name $virtualMachineName -ResourceGroupName $ResourceGroupName -ErrorAction Stop

Once the Backup is successfully configured, as a best practice, we need to trigger an initial Backup of the VM. The same is performed by the below commands.

Write-Host "Fetching the Recovery Services Backup Container"
$namedContainer = Get-AzureRmRecoveryServicesBackupContainer -ContainerType "AzureVM" -Status "Registered" -FriendlyName $virtualMachineName
Write-Host "Fetching the Recovery Services Backup Item"
$item = Get-AzureRmRecoveryServicesBackupItem -Container $namedContainer -WorkloadType "AzureVM"
Write-Host "Triggering a Backup on the VM"
$job = Backup-AzureRmRecoveryServicesBackupItem -Item $item

The script encapsulates all this logic into a reusable function. It also provides the best practices template to invoke this function. Note: Check the comments marked with "ToDo" where you should be making the changes.

Location of the Script

You can find this script in GitHub at this location: Enable-VMBackup.ps1





Comments powered by Disqus