Add-SCAzureNetworkSubnet.ps1


<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID 6acfdc17-82e1-4a7e-ab50-114da3f25f56
 
.AUTHOR Christopher Martin
 
.COMPANYNAME Microsoft
 
.COPYRIGHT
 
.TAGS Azure Networking IPAM IP Vnet Virtual Network
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


#Requires -Module @{ModuleName = 'PSSubnetCarver'; ModuleVersion = '2.0.0'}
#Requires -Module Az.Network
#Requires -Module Az.Resources
#Requires -Module Az.Accounts

<#
 .SYNOPSIS
  Add a subnet to an existing Azure virtual network
 
 .DESCRIPTION
  Use the PSSubnetCarver and Az PowerShell modules together to ingest a virtual network from Azure, add one or more new subnets, then deploy the new subnets to the existing virtual network.
 
 .PARAMETER VirtualNetworkName
  The name of the virtual network to update
 
 .PARAMETER ResourceGroupName
  The name of the resource group that contains the virtual network to update
 
 .PARAMETER Subnet
  A hashtable representing the subnets to be added to the virtual network. The key will be the subnet name, and the value should be a CIDR value (for example, @{default=24})
#>

[CmdletBinding()]
Param(
    [Parameter(Mandatory, Position = 0)]
    [string] $VirtualNetworkName,

    [Parameter(Mandatory, Position = 1)]
    [string] $ResourceGroupName,

    [Parameter(Mandatory, Position = 2)]
    [hashtable] $Subnet
)

$vnet = Get-AzVirtualNetwork -ResourceGroupName $ResourceGroupName -ResourceName $VirtualNetworkName

Set-SCContext -RootAddressSpace $vnet.AddressSpace.AddressPrefixes[0]

$vnet.Subnets | ForEach-Object -Process { $null = Get-SCSubnet -ReserveIPAddress $_.AddressPrefix }

$newNets = $Subnet.Keys | ForEach-Object -Process { $ip = Get-SCSubnet -ReserveCIDR $Subnet[$_]; New-AzVirtualNetworkSubnetConfig -Name $_ -AddressPrefix $ip }

$null = $newNets | ForEach-Object -Process { $vnet.Subnets.Add($_) }

Set-AzVirtualNetwork -VirtualNetwork $vnet