azurepowershellazure-powershellvnet

How to check if Azure Vnet is in use


I am using Az PowerShell module. I want to do the following things.

  1. Verify that the specified azure vnet is not in use.
  2. If it is not in use, delete the VNET.

The easiest way to verify if the VNET is in use, is to use Remove-AzVirtualNetwork in PowerShell and see if it throws an error. I would like to know if there is a better way to do this.


Solution

  • Here is a snippet from a working script is created a while back that does the trick

    $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"
    }
    

    Original script:

    https://raw.githubusercontent.com/hhazeley/HannelsToolBox/master/Functions/Remove-AzureV2VMandResources.ps1