dave562
dave562

Reputation: 33

Powershell (Azure) - Creating VirtualNetwork Objects

I am trying to create a new virtual network object and then attach subnets to it. I need some help with the loop / object creation part. The code below works, but I have to use the Set-AzureRmVirtualNetwork command for every line in my input file. When I moved that Set- command outside of the Foreach loop, it only committed the last subnet (last line of the CSV).

How can I create the object so that multiple subnets are inserted, and then committed once at the end?

function New-NCIAzureNetworks-1 {
    [CmdletBinding()]
    Param (
        # Param1 help description
        [Parameter(Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 0)]
        $csvPath
    )

    $azureSubnets = Import-Csv -Path $csvPath

    Foreach ($azureSubnet in $AzureSubnets) {
        $vnetName = $azureSubnet.Vnetname
        $AddressPrefix = $azureSubnet.AddressPrefix
        $SubnetName = $azureSubnet.SubnetName
        $resourceGroup = $azureSubnet.ResourceGroup

        $vnet = Get-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $resourceGroup

        Add-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $vnet -AddressPrefix $AddressPrefix

        Set-AzureRmVirtualNetwork -VirtualNetwork $vnet
    }
}

Upvotes: 0

Views: 100

Answers (1)

Shui shengbao
Shui shengbao

Reputation: 19195

No, it is not possible. Please refer to this official document.

The Add-AzureRmVirtualNetworkSubnetConfig is then used to add a subnet to the in-memory representation of the virtual network. The Set-AzureRmVirtualNetwork command updates the existing virtual network with the new subnet.

Currently, Add-AzureRmVirtualNetworkSubnetConfig only could store one subnet in-memory. So, you could not use Set-AzureRmVirtualNetwork to add multiple subnets in one command.

But when you create VNet, you could attach multiple subnets in one commands. Please refer to this link.

  New-AzureRmVirtualNetwork -Name MyVirtualNetwork -ResourceGroupName TestResourceGroup 
    -Location centralus -AddressPrefix "10.0.0.0/16" -Subnet $frontendSubnet,$backendSubnet

Upvotes: 1

Related Questions