How do I reconfigure the Azure diagnostics extension when recreating an Azure VM
<p>I need to make changes to a Azure Resource Manager Virtual Machine that are not allowed on an existing machine, such as changing the availability group.  So I have to delete and recreate the machine, attaching the existing disks, network adapters, etc. to the new VM.  I have a PowerShell script to do this, but I'm running into a problem with Virtual Machine extensions.</p>

<p>Here's my code:</p>

<pre><code>$NewVMConfig = New-AzureRmVMConfig -VMName $VM.Name -VMSize $VM.HardwareProfile.VmSize
$NewVMConfig = Set-AzureRmVMOSDisk -VM $NewVMConfig -Name $VM.StorageProfile.OSDisk.Name -VhdUri $VM.StorageProfile.OSDisk.VHD.Uri -CreateOption attach -Windows
foreach ($disk in $vm.StorageProfile.DataDisks) {
    $NewVMConfig = Add-AzureRmVMDataDisk -VM $NewVMConfig -Name $disk.Name -VhdUri $disk.Vhd.Uri -Caching $disk.Caching -DiskSizeInGB $disk.DiskSizeGB -CreateOption attach -Lun $disk.Lun
}
$NewVMConfig.AvailabilitySetReference = $VM.AvailabilitySetReference
$NewVMConfig.DiagnosticsProfile = $VM.DiagnosticsProfile
$NewVMConfig.Extensions = $VM.Extensions
$NewVMConfig.NetworkProfile = $VM.NetworkProfile
$location = $VM.Location
$resourceGroupName = $VM.ResourceGroupName

# Delete machine.  
Remove-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name

# Recreate machine
New-AzureRmVM -ResourceGroupName $resourceGroupName -Location $location -VM $NewVMConfig 
</code></pre>

<p>Notice the line:</p>

<pre><code>$NewVMConfig.Extensions = $VM.Extensions
</code></pre>

<p>The script runs without any error, but the new VM doesn't have the same extensions as the original.  The diagnostics extension is gone and it now has the BGInfo extension which wasn't on the original machine.</p>

<p>I can use the <code>Remove-AzureRmVMExtension</code> command to remove the BGInfo extension, but I have been unsuccessful at recreating the diagnostics extensions.  I've tried both <code>Set-AzureRmVMExtension</code> and <code>Set-AzureRmVMDiagnosticsExtension</code> to no avail.</p>