How to retrieve the Azure VM network security group (NSG) using PowerShell?


To retrieve the Azure VM NSG name using PowerShell, we first need to retrieve the NIC name of the VM.

PS C:\> $vm = Get-AzVM -VMName Win2k16VM1
PS C:\> $vmnic = $vm.NetworkProfile.NetworkInterfaces.Id.Split('/')[-1]

The above command will retrieve the name of the VM. To get the network security Group (NSG) name, we can use the below command.

PS C:\> (Get-AzNetworkInterface -Name $nic).NetworkSecurityGroup.Id.Split('/')[-1]

The above command will retrieve the name of the VM. To get the network security Group (NSG) name, we can use the below command.

PS C:\> (Get-AzNetworkInterface -Name $nic).NetworkSecurityGroup.Id.Split('/')[-1]

You can use the below code to get all the details.

Get-AzVM -VMName Win2k16VM1 | Select Name, ResourceGroupName, `
   @{N='NIC';E={
$_.NetworkProfile.NetworkInterfaces.ID.Split('/')[-1]}}, `
   @{N='NSG';E={
      $nic = $_.NetworkProfile.NetworkInterfaces.ID.Split('/')[-1]
      (Get-AzNetworkInterface -Name
$nic).NetworkSecurityGroup.Id.Split('/')[-1]
   }}

Output

Updated on: 02-Sep-2021

792 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements