Check for Failed Azure Extensions and Remove

This script will check your VMs for a specific failed extensions/CSE and remove them if the virtual machine is running.

# Login to Azure

            # Set the context to the subscription of interest
            Set-AzContext -SubscriptionName "SUBName"

            # Get all resource groups in the subscription
            $resourceGroups = Get-AzResourceGroup

            # Loop through all resource groups
            foreach ($resourceGroup in $resourceGroups) {

                # Get all VMs in the resource group
                $vms = Get-AzVM -ResourceGroupName $resourceGroup.ResourceGroupName

                # Loop through all VMs
                foreach ($vm in $vms) {

                    # Get all extensions for the VM
                    $extensions = Get-AzVMExtension -VMName $vm.Name -ResourceGroupName 

                    # Loop through all extensions
                    foreach ($extension in $extensions) {

                        # Check if the extension is the one we're looking for and if it failed
                        if ($extension.ProvisioningState -eq 'Failed' -and $extension.Name -eq   
                        'InsightAgentWindows') {

                            # Print the details of the VM and the extension
                            Write-Output "VM Name: $($vm.Name), Resource Group: 
                            $($resourceGroup.ResourceGroupName), Extension: $($extension.Name)"

                            # Get the VM status
                            $vmStatus = Get-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName - 

                            # Check if the VM is running
                            if ($vmStatus.Statuses[1].Code -eq 'PowerState/running') {
                                # Remove the extension
                                Remove-AzVMExtension -VMName $vm.Name -ResourceGroupName 
                                $vm.ResourceGroupName -Name 'ExtensionNameHere' -Force
                            } else {
                                Write-Output "VM Name: $($vm.Name) is not running, so the extension was not 
Share or Save this: