How to retrieve the Azure VM vNet name using PowerShell?

To retrieve the Azure Virtual Network (vNet) or subnet name, we need the first name of the network interface of the VM. Below is the command to retrieve the name of the network interface.

$vm = Get-AzVM -VMName Testmachine2k16

TestMachine2k16 is the Azure VM name. Assuming this VM has a single NIC attached.

PS C:\> $nic = $vm.NetworkProfile.NetworkInterfaces
PS C:\> $networkinterface = ($ -split '/')[-1]
PS C:\> $networkinterface

So our NIC name is stored inside the $NetworkInterface variable.

If you have the multiple NICs attached, then use the below command to retrieve the NIC details.

$nics = $vm.NetworkProfile.NetworkInterfaces
foreach($nic in $nics) {
   ($nic.Id -split '/')[-1]

Once we have the nic details we can retrieve the NIC details using the Get-AzNetworkInterface command.

PS C:\> $nicdetails = Get-AzNetworkInterface -Name $networkinterface

vNet name is stored inside the IPConfigurations and Subnet property.

PS C:\> $nicdetails.IpConfigurations.Subnet

We need to retrieve the Subnet from the ID property. Use the below command to retrieve the same.

PS C:\> ($nicdetails.IpConfigurations.subnet.Id -split '/')[-3]

You will get the name of the vNet. For multiple NICs, repeat this process.