Copy managed disks between Azure subscriptions using PowerShell

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.

Script:

#Variables
$SourceRG = ''
$SourceSubscrpitionId = ''
$SourceTenantId = ''
$ManagedDiskName = ''
$DestinationRG = ''
$DestinationSubscriptionId = ''
$DestinationTenantId = ''
$DestinationStorageAccount = ''
$containerName = ''
$vhdName = $ManagedDiskName + '.vhd'

#Source
Select-AzureRMSubscription -Subscription $SourceSubscrpitionId -Tenant $SourceTenantId
$grant = Grant-AzureRmDiskAccess -ResourceGroupName $SourceRG -DiskName $ManagedDiskName -Access Read -DurationInSecond 10800

#Destination
Select-AzureRmSubscription -Tenant $DestinationTenantId  -Subscription $DestinationSubscriptionId
$storageAccount = Get-AzureRmStorageAccount -StorageAccountName $DestinationStorageAccount -ResourceGroupName $DestinationRG
if($storageAccount -eq $null)
{
    New-AzureRmStorageAccount -StorageAccountName $DestinationStorageAccount -ResourceGroupName $DestinationRG -Location "West Europe" -SkuName "Standard_LRS"
}
$storageAccountKey = Get-AzureRmStorageAccountKey -ResourceGroupName $DestinationRG -Name $DestinationStorageAccount
$storageContext = New-AzureStorageContext -StorageAccountName $DestinationStorageAccount -StorageAccountKey $storageAccountKey.Value[0]

$container = Get-AzureStorageContainer $containerName -Context $storageContext -ErrorAction Ignore
if ($container -eq $null)
{
    New-AzureStorageContainer $containerName -Context $storageContext
}

$CopyToBlob = Start-AzureStorageBlobCopy -AbsoluteUri $grant.AccessSAS -DestContainer $containerName -DestBlob $vhdName -DestContext $storageContext

$State = $CopyToBlob | Get-AzureStorageBlobCopyState
While($State.Status -eq "Pending"){
    Start-Sleep 30
    $State = $CopyToBlob | Get-AzureStorageBlobCopyState
    $PercentCompleted = [Math]::Round((($State.BytesCopied/$State.TotalBytes)*100))
    Write-Host "$PercentCompleted % completed for managed disk $ManagedDiskName"
}

Script will show percentage progress of copying vhd file.
Base on results of this script you can easly recreate machine using ARM template like under this link.
You can fo course adjust a script to your needs, eg. use my function for unique storage account generation 🙂

I hope it will be usefull for some of you 😉
Enjoy!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.