New-AzVmBackup-AzAutomationRunbook.ps1
<#PSScriptInfo .VERSION 1.3 .GUID bc7bfe42-ba65-4d0d-adf1-c12adb171c51 .AUTHOR aarambh.verma .COMPANYNAME Horizontal Digital .EXTERNALMODULEDEPENDENCIES Az #> <# .DESCRIPTION This PowerShell script is designed to take an instant snapshot of an Azure Virtual Machine VM which is registered with the Recovery Services Vault with 30 days of retention using Azure Automation Account. .PARAMETER ResourceGroupName Required. The name of the resource group of the Recovery Services Vault. .PARAMETER ResourceName Required. The name of the Recovery Services Vault. .PARAMETER Retention Optional. How many days you need to retain the backup for. The default retention value is 30 days. .NOTES AUTHOR: Aarambh Verma LASTEDIT: Apr 25, 2024 #> Param( [Parameter(Mandatory = $true)] [string]$ResourceGroupName, [Parameter(Mandatory = $true)] [string]$ResourceName, [Parameter(Mandatory = $false)] [int]$Retention = 30 ) # Function to log in to Azure function Login-AzAccount { try { # This script requires system identity enabled for the automation account with 'Automation Contributor' role assignment on the identity. "Logging in to Azure..." Connect-AzAccount -Identity } catch { Write-Error -Message $_.Exception throw $_.Exception } } # Login to Azure Login-AzAccount $targetVault = Get-AzRecoveryServicesVault -ResourceGroupName $ResourceGroupName -Name $ResourceName $containers = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -VaultId $targetVault.ID foreach($container in $containers) { $item = Get-AzRecoveryServicesBackupItem -Container $container -WorkloadType "AzureVM" -VaultId $targetVault.ID $endDate = (Get-Date).AddDays($Retention).ToUniversalTime() Backup-AzRecoveryServicesBackupItem -Item $item -VaultId $targetVault.ID -ExpiryDateTimeUTC $endDate } |