Retrieve 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: 2021-09-02T11:18:54+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements