How to get the Azure VM virtual Network and the Subnet name using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To retrieve the Azure VM virtual network and subnet name, we first need to retrieve the Azure

VM NIC information. To get the Azure VM NIC information, we need to use the Get-AzVM command, and then we can use the NetworkProfile property to retrieve the NIC name as shown below.

PS C:\> $vm = Get-AzVM -Name TestVM
$vmnic = ($'/')[-1]

Once we have the NIC name stored from the above command in the $vmnic variable, we can retrieve the NIC information using the Get-AzNetworkInterface command as shown below.

$vmnicinfo = Get-AzNetworkInterface -Name $vmnic

To get the Virtual Network name attached to the VM use the below operation on the command.


To get the Subnet Attached to the VM use the below operation on the command


The overall script will look like below

$vm = Get-AzVM -Name 'VMName'
$vmnic = ($'/')[-1]
$vmnicinfo = Get-AzNetworkInterface -Name $vmnic
Write-Output "Virtual Network: : $((($'/'))[-3])"
Write-Output "Subnet: $((($'/'))[-1])"
Updated on 01-Sep-2021 09:51:41