我正在使用 Az PowerShell 模块。我想做以下几件事。
验证 VNET 是否正在使用的最简单方法是在 PowerShell 中使用
Remove-AzVirtualNetwork
并查看它是否引发错误。我想知道是否有更好的方法来做到这一点。
我可能建议您使用 Get-AzVirtualNetworkUsageList 来获取每个子网的使用情况。
CurrentValue
的值显示分配的私有IP使用情况。如果它大于 0,则网络应该正在使用中。
如果您还需要检查服务链接
$result = az rest --method get --url
'https://management.azure.com/subscriptions/xxxx-xxx-xxx/resourceGroups/networks-prd-rg-
we/providers/Microsoft.Network/virtualNetworks/ntw_awe_prd_10.24.0.0_18?
api-version=2021-02-01' `
| ConvertFrom-Json
$withServiceLinks = $result.properties.subnets.Where({$null -ne
$PSItem.properties.serviceAssociationLinks})
foreach ($subnet in $withServiceLinks) {
foreach ($serviceAssociationLink in
$subnet.properties.serviceAssociationLinks) {
$serviceAssociationLink.properties.link
}
}
这将显示所有链接的服务。当然,您需要更改 url 或使用 az network vnet 命令来获取所有网络并迭代它们。
#Fetch the VNet Configuration
$VNetDetails=Get-AzVirtualNetwork -Name "<VirtualNetworkName>"-ResourceGroupName "<ResourceGroupName>"
#Fetch the SubnetConfig from the VNETConfig
$VnetSubnetConfig=Get-AzVirtualNetworkSubnetConfig -Name "<SubnetName>" -VirtualNetwork $VNetDetails
#Fetch the IPUsage from the SubnetID.
$PrivateIPUsage=Get-AzVirtualNetworkUsageList -ResourceGroupName "<ResoruceGroupName>" -Name "<VirtualNetworkName>" | where ID -eq $VnetSubnetConfig.id
[int] $TotalIPLimit=$PrivateIPUsage.Limit
[int] $TotalIPUsed=$PrivateIPUsage.CurrentValue
if($TotalIPUsed -lt $TotalIPLimit)
{
Write-Host "Private IP's are available in this Subnet for Usage."
} else {
Write-Host "Private IP's are not available in this Subnet for Usage."
}
这是不久前创建的工作脚本的一个片段,可以实现这一点
$vnetname = ""
$vnetrgname = ""
$VNet = Get-AzVirtualNetwork -Name $vnetname -ResourceGroupName $vnetrgname
$ips = $VNet.Subnets | % {($_.IpConfigurations).Count}
$total = ($ips | Measure-Object -Sum).Sum
if ($total -eq "0")
{
Write-Host -ForegroundColor Green "Virtual Network '$vnetname' not in use, deleting Virtual Network"
Remove-AzVirtualNetwork -Name $vnetname -ResourceGroupName $vnetrgname -Force
}
Else
{
Write-Host -ForegroundColor Yellow -BackgroundColor Black "Virtual Network '$vnetname' in use, Skipping deletion of Virtual Network"
}
原剧本: