Cloud Infrastructure Community's Space

Adding a subnet to Azure Virtual Network with Powershell

Adding a subnet to an Azure virtual network using PowerShell can be done through a few simple steps.

  1. First, you will need to connect to your Azure subscription using the Connect-AzAccount command. This will prompt you to enter your Azure credentials.
  2. Once connected, you can use the Get-AzVirtualNetwork command to retrieve the virtual network that you want to add the subnet to. This command returns information about the virtual network, including its resource group and name.
  3. Next, use the New-AzVirtualNetworkSubnetConfig command to create a new subnet configuration. This command requires the name of the subnet and the address prefix, which is the range of IP addresses that will be assigned to the subnet.
  4. Then, use the Add-AzVirtualNetworkSubnet command to add the new subnet to the virtual network. This command requires the name of the virtual network and the subnet configuration that was created in the previous step.
  5. Finally, use the Set-AzVirtualNetwork command to apply the changes to the virtual network. This command requires the name of the virtual network and the subnet configuration that was added in the previous step.

It is important to note that all the above steps should be wrapped in a try catch block to handle any errors that may occur during the process.

Example:


try {
    Connect-AzAccount
    $vnet = Get-AzVirtualNetwork -Name "MyVirtualNetwork" -ResourceGroupName "MyResourceGroup"
    $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name "MySubnet" -AddressPrefix "10.0.1.0/24"
    Add-AzVirtualNetworkSubnet -VirtualNetwork $vnet -Subnet $subnetConfig
    Set-AzVirtualNetwork -VirtualNetwork $vnet
} catch {
    Write-Error $_.Exception
}

In this example, we first connect to the Azure subscription using the Connect-AzAccount command. We then retrieve the virtual network “MyVirtualNetwork” in the resource group “MyResourceGroup” using the Get-AzVirtualNetwork command. We then create a new subnet configuration for the subnet “MySubnet” with the address prefix “10.0.1.0/24” using the New-AzVirtualNetworkSubnetConfig command. We then add the new subnet to the virtual network using the Add-AzVirtualNetworkSubnet command and apply the changes to the virtual network using the Set-AzVirtualNetwork command.

This is a basic example of how to add a subnet to an Azure virtual network using PowerShell. You can use these commands to customize the process to fit your specific needs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Press ESC to close