How To Get Subnet ID In Azure PowerShell

Recently, I got the requirement to get the subnet id in Azure using PowerShell. This article will help you to get subnet id in Azure PowerShell.

How To Get Subnet ID In Azure PowerShell

To get Subnet ID in Azure PowerShell, we can use the Get-AzVirtualNetworkSubnetConfig command along with the complete script below.

$mySubnet = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix "10.0.1.0/24"
$myvirtualNetwork = New-AzVirtualNetwork -Name test -ResourceGroupName MyNewResGrp -Location EastUS -AddressPrefix "10.0.0.0/16" -Subnet $mySubnet
$subnetConfig = Get-AzVirtualNetworkSubnetConfig -Name mySubnet -VirtualNetwork $myvirtualNetwork
$subnetId = $subnetConfig.Id 
Write-Output "Subnet ID: $subnetId" 

After executing the above query, I got the expected output, as shown below.

Subnet ID: /subscriptions/1cdf4300-dee5-4518-9c9c-feaa72a5cbd1/resourceGroups/MyNewResGrp/providers/Microsoft
.Network/virtualNetworks/test/subnets/mySubnet

You can see the same output as shown in the screenshot below.

How To Get Subnet ID In Azure PowerShell

OR, You can also use the Get-AzVirtualNetwork command along with the script below to achieve this.

$subnetId = (Get-AzVirtualNetwork -Name "test" -ResourceGroupName "MyNewResGrp" | 
             Select-Object -ExpandProperty Subnets | 
             Where-Object { $_.Name -eq "mySubnet" }).Id
             Write-Output "Subnet ID: $subnetId"

After executing the above query, I got the expected output, as shown in the screenshot below.

Get Subnet ID In Azure PowerShell

OR, We can also use the below query for this purpose.

$vnet = Get-AzVirtualNetwork -Name "test" -ResourceGroupName "MyNewResGrp"
$subnets = $vnet.Subnets | Select-Object Id
Write-Output "Subnet ID: $subnets"

After executing the above query, I got the expected output, as shown in the screenshot below.

how to get subnet id in azure

You may also like following the articles below.

Azure Virtual Machine

DOWNLOAD FREE AZURE VIRTUAL MACHINE PDF

Download our free 25+ page Azure Virtual Machine guide and master cloud deployment today!