In this example, the powershell Cmdlets edit the VM NIC properties and change the subnet from one vNet to another vNet.
Step1: Get Azure VM, NIC and Resource Group Properties.
Stop-AzVM -Name “vm” -ResourceGroupName “RG01”
$vm = Get-AzVm -Name “vm” -ResourceGroupName “RG01”
$myVnet = Get-AzVirtualNetwork -Name “VNET” -ResourceGroupName “RG01”
$backEnd = $myVnet.Subnets | ?{$_.Name -eq ‘Prod’}
# Create a virtual NIC
$myNic3 = New-AzNetworkInterface -ResourceGroupName “RG01” -Name “vNIC-01” -Location “AustraliaEast” -SubnetId $backEnd.Id
# Get the ID of the new virtual NIC and add to VM
$nicId = (Get-AzNetworkInterface -ResourceGroupName “RG01” -Name “vNIC-01”).Id
Add-AzVMNetworkInterface -VM $vm -Id $nicId | Update-AzVm -ResourceGroupName “RG01”
Step2 : Setup Values of Target vNet to be applied to the Azure VM
$vm.NetworkProfile.NetworkInterfaces
# Set NIC 0 to be primary
$vm.NetworkProfile.NetworkInterfaces[0].Primary = $true
$vm.NetworkProfile.NetworkInterfaces[1].Primary = $false
Step3: Apply the changes. The VM will be restarted once you execute the PowerShell command.
# Update the VM state in Azure
Update-AzVM -VM $vm -ResourceGroupName “RG01”
Start-AzVM -ResourceGroupName “RG01” -Name “vm”
Step4: Check the properties of the Azure VM.