Search code examples
azurepowershellnetwork-programmingazure-runbook

How to create multiple Subnets in pre-existing Vnet Powershell


I have the following code which works good for adding a few subnets but I would like for this script to leverage a CSV file to import from and add the subnets into a pre-existing Vnet?



$appssubnet = New-AzVirtualNetworkSubnetConfig -Name servers -AddressPrefix "172.16.1.0/24" -NetworkSecurityGroupId "/subscriptions/xxxxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/powershell-grp/providers/Microsoft.Network/networkSecurityGroups/app-nsg1"`
-RouteTableId "/subscriptions/xxxxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/powershell-grp/providers/Microsoft.Network/routeTables/powershell-rt"
$serversubnet = New-AzVirtualNetworkSubnetConfig -Name apps -AddressPrefix "172.16.2.0/24" -RouteTableId "/subscriptions/xxxxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/powershell-grp/providers/Microsoft.Network/routeTables/powershell-rt"
$dmz = New-AzVirtualNetworkSubnetConfig -Name dmz -AddressPrefix "172.16.3.0/24"
$updatedvnet = New-AzVirtualNetwork -Name "testsubnet" -ResourceGroupName "powershell-grp" -Location "North Europe" -AddressPrefix "172.16.0.0/16" -Subnet $serversubnet, $dmz, $appssubnet -Force:$true
$updatedvnet | Set-AzVirtualNetwork



Solution

  • You can use the below powershell script.

      $subnets1 = Import-Csv "C:\Users\v-XXXsXX18\Documents\TestCount.csv"
        #$subnets1.subnetName
        foreach ($subnet in $subnets1){
        $dmz = New-AzVirtualNetworkSubnetConfig -Name $subnet.SubnetName -AddressPrefix $subnet.AddressPrefix
        
        $vnet=Get-AzVirtualNetwork -Name "MyVirtualNetworkTes" -ResourceGroupName "v-raXXXXndtree"
        $updatedvnet=Add-AzVirtualNetworkSubnetConfig -Name $dmz.Name -VirtualNetwork $vnet -AddressPrefix $dmz.AddressPrefix
        
        $updatedvnet | Set-AzVirtualNetwork
        
        
        }
    

    enter image description here

    Output--

    enter image description here

    enter image description here