New-AzVmBackup-AzAutomationRunbook.ps1
<#PSScriptInfo .VERSION 1.0 .GUID bc7bfe42-ba65-4d0d-adf1-c12adb171c51 .AUTHOR aarambh.verma .COMPANYNAME .COPYRIGHT .TAGS .LICENSEURI .PROJECTURI .ICONURI .EXTERNALMODULEDEPENDENCIES .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES #> <# .DESCRIPTION "The PowerShell script is designed to take an instant snapshot of an Azure 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. .NOTES AUTHOR: Aarambh Verma LASTEDIT: Apr 25, 2024 #> Param( [Parameter(Mandatory = $true)] [string]$ResourceGroupName, [Parameter(Mandatory = $true)] [string]$ResourceName ) # 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 # how many days to retain backup - default is 30 days $endDate = (Get-Date).AddDays(30).ToUniversalTime() Backup-AzRecoveryServicesBackupItem -Item $item -VaultId $targetVault.ID -ExpiryDateTimeUTC $endDate } |