How to automate taking snapshots in Azure?

How we can automate taking snapshots in azure for backup purpose? 

Automate taking snapshot in azure manual and automated.

Script that will require to put in runbook:

$resourceGroupName = 'ABC' 

$location = 'eastus' 

$vmName = 'VM-Name'

$datetime = Get-Date -Format "MM-dd-yyyy-HH-mm"

$snapshotName = 'Snapshot-' + $datetime

 

# Ensures you do not inherit an AzContext in your runbook

Disable-AzContextAutosave -Scope Process

# Connect to Azure with user-assigned managed identity

$AzureContext = (Connect-AzAccount -Identity -AccountId 'Put Account ID' -SubscriptionName 'Subscription Name').context

#Write-Output $AzureContext

 

# set and store context

$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext   

# Get the VM you want to take snapshot of OS Disk

$vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName

#Write-Output $vm

$snapshot =  New-AzSnapshotConfig -SourceUri $vm.StorageProfile.OsDisk.ManagedDisk.Id -Location $location -CreateOption copy

New-AzSnapshot `

    -Snapshot $snapshot `

    -SnapshotName $snapshotName `

    -ResourceGroupName $resourceGroupName