Create a custom image from a VHD file with PowerShell
Article
In Azure DevTest Labs, you can use custom images to:
Create a VM from a VHD file that has all the software you need preinstalled.
Create VMs quickly, because you don't have to install all the required software on the target machines.
Clone a VM by creating a custom image from a VM, and then creating VMs based on that image.
Prerequisites
To work through this tutorial, you need a virtual hard disk (VHD) file uploaded to the Azure Storage account for the lab where you want to create the custom image. To upload a VHD file to your storage account, follow the instructions in one of these articles:
Get the lab object by calling the Get-AzResource cmdlet. Replace the <lab resource group name> and <lab name> placeholders with your own resource group and lab names.
Replace the placeholder for the $vhdUri variable with the URI of your uploaded VHD file. You can get the VHD file's URI from its blob page in the lab's storage account in the Azure portal. An example VHD URI is: https://acontosolab1234.blob.core.windows.net/uploads/myvhd.vhd.
$vhdUri = '<VHD URI>'
Create the custom image by using the New-AzResourceGroupDeployment cmdlet. Replace the <custom image name> and <custom image description> placeholders with the name and description you want.
Combining the preceding steps produces the following PowerShell script that creates a custom image from a VHD file. To use the script, replace the following placeholders with your own values:
<subscription ID>
<lab resource group name>
<lab name>
<VHD URI>
<custom image name>
<custom image description>
# Log in to your Azure account.
Connect-AzAccount
# Select the desired Azure subscription.
$subscriptionId = '<subscription ID>'
Select-AzSubscription -SubscriptionId $subscriptionId
# Get the lab object.
$labRg = '<lab resource group name>'
$labName = '<lab name>'
$lab = Get-AzResource -ResourceId ('/subscriptions/' + $subscriptionId + '/resourceGroups/' + $labRg + '/providers/Microsoft.DevTestLab/labs/' + $labName)
# Set the URI of the VHD file.
$vhdUri = '<VHD URI>'
# Set the custom image name and description values.
$customImageName = '<custom image name>'
$customImageDescription = '<custom image description>'
# Set up the parameters object.
$parameters = @{existingLabName="$($lab.Name)"; existingVhdUri=$vhdUri; imageOsType='windows'; isVhdSysPrepped=$false; imageName=$customImageName; imageDescription=$customImageDescription}
# Create the custom image.
New-AzResourceGroupDeployment -ResourceGroupName $lab.ResourceGroupName -Name CreateCustomImage -TemplateUri 'https://raw.githubusercontent.com/Azure/azure-devtestlab/master/samples/DevTestLabs/QuickStartTemplates/201-dtl-create-customimage-from-vhd/azuredeploy.json' -TemplateParameterObject $parameters