Moving VM disk to remote subscription

Hey Folks! In todays article I want to show you how to copy managed disks between Azure subscriptions using PowerShell.

Script is very easy in use. The only things which you should provide are variables on the beginning like subscription ids, resource groups etc. As a result .vhd file will be created under destination container on storage account.

Remember that Azure account under which script for copy managed disks between Azure subscriptions will be run should have permission in both subscriptions, otherwise script will retun error.

Let’s rock!

$SourceRG = ''
$SourceSubscrpitionId = ''
$SourceTenantId = ''
$ManagedDiskName = ''
$DestinationRG = ''
$DestinationSubscriptionId = ''
$DestinationTenantId = ''
$DestinationStorageAccount = ''
$containerName = ''
$vhdName = $ManagedDiskName + '.vhd'
Select-AzSubscription -Subscription $SourceSubscrpitionId -Tenant $SourceTenantId
$grant = Grant-AzDiskAccess -ResourceGroupName $SourceRG -DiskName $ManagedDiskName -Access Read -DurationInSecond 10800
Select-AzSubscription -Tenant $DestinationTenantId  -Subscription $DestinationSubscriptionId
$storageAccount = Get-AzStorageAccount -StorageAccountName $DestinationStorageAccount -ResourceGroupName $DestinationRG
if($storageAccount -eq $null)
New-AzStorageAccount -StorageAccountName $DestinationStorageAccount -ResourceGroupName $DestinationRG -Location "West Europe" -SkuName "Standard_LRS"
$storageAccountKey = Get-AzStorageAccountKey -ResourceGroupName $DestinationRG -Name $DestinationStorageAccount
$storageContext = New-AzStorageContext -StorageAccountName $DestinationStorageAccount -StorageAccountKey $storageAccountKey.Value[0]
$container = Get-AzStorageContainer $containerName -Context $storageContext -ErrorAction Ignore
if ($container -eq $null)
New-AzStorageContainer $containerName -Context $storageContext
$CopyToBlob = Start-AzStorageBlobCopy -AbsoluteUri $grant.AccessSAS -DestContainer $containerName -DestBlob $vhdName -DestContext $storageContext
$State = $CopyToBlob | Get-AzStorageBlobCopyState
While($State.Status -eq "Pending"){
Start-Sleep 30
$State = $CopyToBlob | Get-AzStorageBlobCopyState
$PercentCompleted = [Math]::Round((($State.BytesCopied/$State.TotalBytes)*100))
Write-Host "$PercentCompleted % completed for managed disk $ManagedDiskName"


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s