Move or Add a VM’s Primary NIC from one VNET to another vNet


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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.