Skip to content

Instantly share code, notes, and snippets.

@transiient
Created January 3, 2023 11:33
Show Gist options
  • Save transiient/ea8873b63644afe91b0ea9e383d675d3 to your computer and use it in GitHub Desktop.
Save transiient/ea8873b63644afe91b0ea9e383d675d3 to your computer and use it in GitHub Desktop.
# Azure Backup Runbook Script
# github.com/transiient
# https://gist.github.com/transiient/ea8873b63644afe91b0ea9e383d675d3
# 1. Fill in the information in the block below
# 2. Add to Runbook (MAKE SURE the Az module and its descentants are installed in the parent Automation Account)
# 3. Add a Schedule and link the Runbook
### !!! Fill me in !!! ###
$SubscriptionName = "" # VM and RSV should be in the same Subscription
$VM_Name = ""
$DaysToKeep = 7 # Number of days to keep this backup
# You might need to go to "JSON View" to see the below information. The RSG is in the "Resource ID"
$RSV_ResourceGroupName = ""
$RSV_Name = ""
### !!! --- -- --- !!! ###
# Don't edit anything below here (unless you know what you're doing)
$ErrorActionPreference = "Stop"
# Connect Managed Identity
try {
Connect-AzAccount -Identity -Subscription $SubscriptionName
Write-Output "Successfully connected the Azure Managed Identity."
} catch {
Write-Error -Exception $_.Exception
throw $_.Exception
}
try {
$_RSV = Get-AzRecoveryServicesVault -ResourceGroupName $RSV_ResourceGroupName -Name $RSV_Name
$_BackupContainer = Get-AzRecoveryServicesBackupContainer -VaultId $_RSV.ID -ContainerType AzureVM -FriendlyName $VM_Name
$_BackupItem = Get-AzRecoveryServicesBackupItem -VaultId $_RSV.ID -WorkloadType AzureVM -Container $_BackupContainer
Backup-AzRecoveryServicesBackupItem -VaultId $_RSV.ID -Item $_BackupItem -ExpiryDateTimeUTC (Get-Date).AddDays($DaysToKeep)
Write-Output "Success"
} catch {
Write-Error -Exception $_.Exception
throw $_.Exception
}
Write-Output "Runbook run complete at $(Get-Date -format 'u')"
Exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment