Moving VM disk to remote subscription

Posted by

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!

#Variables
$SourceRG = ''
$SourceSubscrpitionId = ''
$SourceTenantId = ''
$ManagedDiskName = ''
$DestinationRG = ''
$DestinationSubscriptionId = ''
$DestinationTenantId = ''
$DestinationStorageAccount = ''
$containerName = ''
$vhdName = $ManagedDiskName + '.vhd'
#Source
Select-AzSubscription -Subscription $SourceSubscrpitionId -Tenant $SourceTenantId
$grant = Grant-AzDiskAccess -ResourceGroupName $SourceRG -DiskName $ManagedDiskName -Access Read -DurationInSecond 10800
#Destination
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
}
#copy
$CopyToBlob = Start-AzStorageBlobCopy -AbsoluteUri $grant.AccessSAS -DestContainer $containerName -DestBlob $vhdName -DestContext $storageContext
#copystate
$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:

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s