有没有办法查询azure虚拟网络的下一个可用子网范围



我有一个在azure中配置的虚拟网络(VNET(,地址空间为10.0.0.0/8,我只用于一种(穷人的(IPAM功能。我在NVET中配置了几个子网,10.14.1.0/24、10.14.2.0/24、1014.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.0/24(?

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

$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   

最新更新