GinShell.Azure/Public/Invoke-GsAzureVmDiskToStorageAsSnapshotBlob.ps1
|
function Invoke-GsAzureVmDiskToStorageAsSnapshotBlob { [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string]$TenantId = (Read-Host "Provide the source VM tenant ID"), [Parameter(Mandatory = $false)] [string]$SubscriptionId = (Read-Host "Provide the source VM subscription ID"), [Parameter(Mandatory = $false)] [string[]]$VmName = ((Read-Host "Provide source VM names (comma-separated)").Split(',') | ForEach-Object { $_.Trim() }), [Parameter(Mandatory = $false)] [string]$StorageAccountName = (Read-Host "Provide the destination Storage Account name"), [Parameter(Mandatory = $false)] [string]$ContainerName = (Read-Host "Provide the destination Container name"), [Parameter(Mandatory = $false)] [string]$StorageAccountKey = (Read-Host "Provide the destination Storage Account key") ) try { Write-GsLog -Message "Authenticating to Azure with Tenant: $TenantId and Subscription: $SubscriptionId" -Type Action Connect-GsAzureAccount -TenantId $TenantId -SubscriptionId $SubscriptionId } catch { Write-GsLog -Message "Failed to authenticate to Azure: $($_.Exception.Message)" -Type Error return } try { Write-GsLog -Message "Fetching VM information for: $($VmName -join ', ')" -Type Info $vmInfo = Get-GsAzureVmFullInfo -VmName $VmName if (-not $vmInfo -or -not $vmInfo.Disks) { Write-GsLog -Message "No disks found for the specified VMs." -Type Error return } } catch { Write-GsLog -Message "Error fetching VM information: $($_.Exception.Message)" -Type Error return } try { Write-GsLog -Message "Creating snapshots from attached disks..." -Type Info $snapshots = ConvertTo-GsAzureDiskToSnapshot -Disk $vmInfo.Disks if (-not $snapshots -or $snapshots.Count -eq 0) { Write-GsLog -Message "No snapshots were created." -Type Error return } } catch { Write-GsLog -Message "Error creating snapshots: $($_.Exception.Message)" -Type Error return } try { Write-GsLog -Message "Starting snapshot copy to storage account '$StorageAccountName' in container '$ContainerName'" -Type Info $blobs = Send-GsAzureSnapshotsToStorage -Snapshot $snapshots -StorageAccountName $StorageAccountName -ContainerName $ContainerName -StorageAccountKey $StorageAccountKey -WaitForComplete Write-GsLog -Message "Snapshots successfully transferred. Total blobs: $($blobs.Count)" -Type Success } catch { Write-GsLog -Message "Snapshot copy failed: $($_.Exception.Message)" -Type Error } try { Write-GsLog -Message "Starting deletion of temporary snapshots..." -Type Warning foreach ($snap in $snapshots) { Write-GsLog -Message "Deleting snapshot '$($snap.Name)' in resource group '$($snap.ResourceGroupName)'" -Type Action } Remove-GsAzureSnapshot -Snapshot $snapshots Write-GsLog -Message "All snapshots successfully deleted." -Type Success } catch { Write-GsLog -Message "Snapshot deletion failed: $($_.Exception.Message)" -Type Error } return $blobs } |