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 = ($vm.NetworkProfile.NetworkInterfaces.id).Split('/')[-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.

(($vmnicinfo.IpConfigurations.subnet.id).Split('/'))[-3]

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

(($vmnicinfo.IpConfigurations.subnet.id).Split('/'))[-1]

The overall script will look like below

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

Advertisements