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:-
- $myLoadBalancer = Get-AzureRmLoadBalancer -ResourceGroupName ‘MyTempResourceGroup’ -Name ‘MyTempLoadBalancer’
- if($myLoadBalancer.BackendAddressPools.Backendipconfigurations -eq $null)
- {
- Write-Host “Load Balancer is empty”
- }
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:-
- 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. Declare Variables
- $subscriptionName = ‘MyTestSubscription’
- #2. Selecting Subscription
- $ignoreOutput = Select-AzureRmSubscription -SubscriptionName $subscriptionName
- #3. Searching ResourceGroups in Subscription
- $resourceGroups = Get-AzureRmResourceGroup
- #4. Iterate through all resource groups to find empty Load Balancers
- foreach($currentResourceGroup in $resourceGroups)
- {
- #5. Searching LoadBalancers
- $loadBalancers = Get-AzureRmLoadBalancer -ResourceGroupName $currentResourceGroup.ResourceGroupName
- foreach($currentLoadBalancer in $loadBalancers)
- {
- #6. Validating if LoadBalancer is empty
- if($currentLoadBalancer.BackendAddressPools.Backendipconfigurations -eq $null)
- {
- #7. Deleting empty LoadBalancer in Azure
- Remove-AzureRmLoadBalancer -Name $currentLoadBalancer.Name -ResourceGroupName $currentResourceGroup.ResourceGroupName -Force
- }
- }
- }
Happy Coding!!!
No comments:
Post a Comment