Automatically trigger on-demand Azure VM Backup for multiple VMs - Code Sample
@20aman Aug 23, 2021Over the period of time, you will have multiple VMs being protected in Azure Recovery Services Vault using the Backup services i.e. the daily Azure VM Backup. Before performing any major activity in your environment, you will want to take an on-demand backup with an extended expiry date. This helps you to have a fallback option if anything goes wrong during the activity.
The script I present in this post automates the triggering of this on-demand backup for multiple VMs and also lets you specify a date for the expiry of this backup. The script takes the name of VMs in a csv file as input.
Script location
The latest version of the script can be found in GitHub here: Trigger-AzVMOnDemandBackup
The input CSV file is also located at the same location. Use this file to provide the VM names as an input to the script. Update the path to this file in the script input variables.
Script Working
The script starts by checking if the input config file (with VM names) exists or not. If not, then the script prints the message to check the path and exit. It then imports the CSV file. Then it sets the context to the right recovery services vault and starts iterating through the VMs. Then it fetches the backup container for the current VM using the below command.
$backupcontainer = Get-AzRecoveryServicesBackupContainer `
-ContainerType "AzureVM" `
-FriendlyName $vmName
It uses the container to fetch the backup item corresponding to the current VM.
$item = Get-AzRecoveryServicesBackupItem `
-Container $backupcontainer `
-WorkloadType "AzureVM"
Finally, it triggers the on-demand backup using the Backup-AzRecoveryServicesBackupItem cmdlet.
Backup-AzRecoveryServicesBackupItem -Item $item -ExpiryDateTimeUTC $dateTillExpiry
I hope this script helps you save lots of time during on-demand backup creation. If you have any improvements you would like to see in the script feel free to provide that as a comment here or a pull request on GitHub.