Skip to content

Instantly share code, notes, and snippets.

@dollarpo7
Created June 24, 2020 09:30
Show Gist options
  • Save dollarpo7/6afa7954c2538b37fdbb2e4ff92bbf7e to your computer and use it in GitHub Desktop.
Save dollarpo7/6afa7954c2538b37fdbb2e4ff92bbf7e to your computer and use it in GitHub Desktop.
DiskSnapshot2
#Get service principal details from shared resources
$cred = Get-AutomationPSCredential -Name 'SPCreds'
$tenantId = Get-AutomationVariable -Name 'TenantId'
#Auth with service principal
Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tenantId
#Get all Windows VMs in the Subscription
$vms = Get-AzVM | Where-Object {$_.StorageProfile.OsDisk.OsType -eq 'Windows'}
#Loop over each VMs data disks and cut a snapshot of them
foreach($vm in $vms) {
$vmName = $vm.name
$vm.StorageProfile.DataDisks | ForEach-Object {
$snapConfig = New-AzSnapshotConfig -SourceUri $_.ManagedDisk.id -Location 'westus2' -CreateOption copy
$snap = New-AzSnapshot -Snapshot $snapConfig -SnapshotName "$vmName-$($_.name)-snap-$((Get-Date).ToString('MM-dd-yyyy'))" -ResourceGroupName webservers
Set-AzResource -ResourceId $snap.Id -Tag @{Created=(Get-Date).ToLongDateString()} -Force
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment