Powershell – Azure VM change OS Disk

azurehard drivepowershellvirtual-machines

I've create an Azure VM in RM and have deleted the VM and Components expect the OSDisk in an Premium Storage Account (Blobs).
Now i wouldd like to create an new VM and attach the OS Disk to the new VM.

I've tried to use the Set-AzureRmVmOsDisk, to an existing VM. That does not work.
I also tried creating a new VM and modify the OSDisk. But there is the Error:

New-AzureRmVM : Changing property 'osDisk.name' is not allowed.

Any idea on how to create an new VM and assign an OS .vhd from an old VM as new System Disk`?

EDIT:
I've tried the following:

$VM = Get-AzureRmVM -Name "VM01" -ResourceGroupName "TestResource1"
Set-AzureRmVMOSDisk -VM $VM -Name "**VM123456**.vhd" -VhdUri "https://vm01disk.blob.core.windows
.net/vhds/**VM123456**.vhd" -CreateOption Attach

The output show:

 "osDisk": {
   "osType": null,
   "encryptionSettings": null,
   "name": "VM123456.vhd",
   "vhd": {
     "uri": "https://vm01disk.blob.core.windows.net/vhds/**VM123456**.vhd"
   },

After running the command:

Get-AzureRmVM -Name "VM01" -ResourceGroupName "TestResource1"

again, i can see:

"osDisk": {
  "osType": "Windows",
  "encryptionSettings": null,
  "name": "VM01",
  "vhd": {
    "uri": "https://vm01disk.blob.core.windows.net/vhds/**VMoldID**.vhd"
  },

There was no Error, and the prompt from the command indicates the changes have been done. But when calling the infos from the VM again, there is still the old vhd

Best Answer

To create a new VM, using the existing disk you should be able to do so with the following PowerShell (this is simplified, I haven't added any NICS etc.).

$vm = New-AzureRMVMConfig -VMName $vmName -VMSize $vmSize
$osDiskUri = "https://nameofyourstorageaccount.blob.core.windows.net/vhds/nameofyourvhd.vhd"
$vm = Set-AzureRMVMOSDisk -VM $vm -Name $osDiskName -VhdUri $osDiskUri -CreateOption attach -Windows
New-AzureRMVM -ResourceGroupName $rgName -Location $location -VM $vm 
Related Topic