有没有一种方法可以查询Azure虚拟网络的下一个可用子网范围

时间:2020-08-08 20:42:51

标签: powershell network-programming azure-virtual-network

我有一个配置为天蓝色的虚拟网络(VNET),其地址空间为10.0.0.0/8,我仅将其用于某种(穷人)的IPAM功能。 我在NVET,10.14.1.0 / 24、10.14.2.0 / 24、10.14.3.0 / 24,...中配置了几个子网...

我想做的是查询NVET的下一个可用子网“插槽”(例如,正在使用10.14.12.0/24,但尚未使用10.14.13.0/24),然后存储该“插槽”作为变量,并通过使用给定名称创建子网来保留它。

$vnet = Get-AzVirtualNetwork -Name IPAM-vnet
$sublist = Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet | Where-Object {$_.AddressPrefix -gt "10.14*"} | Sort-Object -Property AddressPrefix -Descending
$lastsub = $sublist[0].AddressPrefix

PS C:\> write-host $lastsub
10.14.12.0/24

如何将字符串中的第三个八位字节(10.14。 12 .0 / 24)递增到(10.14。 13 .0 / 24)?

1 个答案:

答案 0 :(得分:0)

有几种方法可以获取第三个八位字节。

$template = @'
10.14.{third:12}.0/24
'@
$thirdoctet = '10.14.12.0/24' | ConvertFrom-String -TemplateContent $template | select -Expand third

$thirdoctet = if('10.14.12.0/24' -match '(\d{2,3})(?=.\d*\/24)'){$matches.1}

$thirdoctet = '10.14.12.0/24' -split '\.' | select -Skip 2 -First 1

get-variable thirdoctet

Name                           Value                                                                                                                                                          
----                           -----                                                                                                                                                          
thirdoctet                     12   

现在您只可以添加1。但是,由于其中一些实际上是字符串,因此您可能最终得到

 $thirdoctet + 1

 121

如果将整数放在左侧,则也可以将右侧强制为整数。

$nextoctet = 1 + $thirdoctet
$nextoctet
13

现在您可以替换八位字节

$newsubnet = $lastsub -replace $thirdoctet,$nextoctet

要一次性增加并最终得到所需的字符串,我将使用regex方法

$newsubnet = $lastsub -replace '(\d{2,3})(?=.\d*\/24)',(1+$matches.1)
get-variable newsubnet

Name                      Value                                                                                                                                                          
----                          -----                                                                                                                                                          
newsubnet              10.14.13.0/24   
相关问题