How to create an Azure VM from an existing managed disk with PowerShell?

62 Views Asked by At

What I've tried at first:

# fetch existing disk and network interface
$disk = Get-AzDisk -DiskName "MyDiskName" -ResourceGroupName "MyRgName"
$ni = Get-AzNetworkInterface -Name "MiNiName" -ResourceGroupName "MyRgName"

# create vm configuration
$vmConfig = New-AzVMConfig -VMName "MyVmName" -VMSize "Standard_D2_v5" -SecurityType "TrustedLaunch" | `
Set-AzVMBootDiagnostic -Enable -ResourceGroupName "MyRgName" | `
Set-AzVMOSDisk -CreateOption "Attach" -ManagedDiskId $disk.Id | `
Add-AzVMNetworkInterface -Id $ni.Id.

# create vm
New-AzVM -VM $vmConfig -ResourceGroupName "MyRgName" -Location "Australia East"

However, the New-AzVM command fails with this:

Required parameter 'osDisk.osType' is missing (null).
ErrorCode: InvalidParameter
ErrorMessage: Required parameter 'osDisk.osType' is missing (null).
ErrorTarget: osDisk.osType
StatusCode: 400 ReasonPhrase:
OperationID : d5e4e899-6c4e-42e8-94fd-47f0350ab7a5

Then, if I try adding the OS flag to the Set-AzVMOSDisk as follows...

Set-AzVMOSDisk -Windows -CreateOption "Attach" -ManagedDiskId $disk.Id

I get the following error:

Set-AzVMOSDisk:
Line 3
Set-AzVMOSDisk -Windows -CreateOption "Attach" -ManagedDiskId $disk.I …
Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.

That flag does seem unnecessary, since I am not trying to create a VM off an empty disk, and the existing disk already has that information in it:

"name": "MyDiskName",
"type": "Microsoft.Compute/disks",
"location": "australiaeast",
"sku": {
   "name": "StandardSSD_LRS",
   "tier": "Standard"
},
"properties": {
   "osType": "Windows",
   "hyperVGeneration": "V2",
   "supportedCapabilities": {
      "diskControllerTypes": "SCSI",
      "acceleratedNetwork": true,
      "architecture": "x64"
   }
1

There are 1 best solutions below

0
Venkat V On

How to create an Azure VM from an existing managed disk with PowerShell?

Here is the updated PowerShell script to create Azure VM from an existing managed disk.

$VMName ="venkatdemo"
$azureVmSize = "Standard_D2_v5"
$Rgname = "rg-name"
    
$disk = Get-AzDisk -DiskName "venkat-vm-os-disk" -ResourceGroupName $Rgname
$ni = Get-AzNetworkInterface -Name "VM_Nic" -ResourceGroupName $Rgname
$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $azureVmSize -SecurityType "Standard"
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $ni.Id 
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -ManagedDiskId $disk.Id -StorageAccountType "Standard_LRS" -Name $disk.Name -CreateOption Attach -Windows -DeleteOption Delete -Verbose
New-AzVM -ResourceGroupName $Rgname  -Location "westus2" -VM $VirtualMachine -Verbose

Output:

enter image description here