Delete Empty Load Balancers with No Virtual Machines


Hi All,

Below script will help you to find and delete empty load balancers with no virtual machines from Azure environment.

 

Find Empty Load Balancers

You can find an empty load balancer by checking its BackEndIPConfigurations. Example:-

  1. $myLoadBalancer = Get-AzureRmLoadBalancer -ResourceGroupName ‘MyTempResourceGroup’ -Name ‘MyTempLoadBalancer’
  2. if($myLoadBalancer.BackendAddressPools.Backendipconfigurations -eq $null)
  3. {
  4.     Write-Host “Load Balancer is empty”
  5. }

 

Delete Empty Load Balancer

Remove-AzureRmLoadBalancer command deletes a load balancer. You will be required to pass name of the load balancer and resource group name. Example:-

  1. Remove-AzureRmLoadBalancer -Name ‘MyTempLoadBalancer’ -ResourceGroupName ‘MyTempResourceGroup’ -Force 

 

Full Script

Below script will find and delete empty load balancers in a given Subscription in Azure

  1. #1. Declare Variables
  2. $subscriptionName = ‘MyTestSubscription’
  3. #2. Selecting Subscription
  4. $ignoreOutput = Select-AzureRmSubscription -SubscriptionName $subscriptionName
  5. #3. Searching ResourceGroups in Subscription
  6. $resourceGroups = Get-AzureRmResourceGroup
  7. #4. Iterate through all resource groups to find empty Load Balancers
  8. foreach($currentResourceGroup in $resourceGroups)
  9. {
  10.     #5. Searching LoadBalancers
  11.     $loadBalancers = Get-AzureRmLoadBalancer -ResourceGroupName $currentResourceGroup.ResourceGroupName
  12.     foreach($currentLoadBalancer in $loadBalancers)
  13.     { 
  14.         #6. Validating if LoadBalancer is empty
  15.         if($currentLoadBalancer.BackendAddressPools.Backendipconfigurations -eq $null)
  16.         {
  17.             #7. Deleting empty LoadBalancer in Azure
  18.             Remove-AzureRmLoadBalancer -Name $currentLoadBalancer.Name -ResourceGroupName $currentResourceGroup.ResourceGroupName -Force
  19.         }           
  20.     }
  21. }    

 

Happy Coding!!!


Comments (0)

Skip to main content