Remove-UnattachedDisks.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID db5349d5-35e0-406d-88dd-88bd2aa188ac
 
.AUTHOR Yoel Borovsky
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>
 

#Requires -Module Az.Compute
#Requires -Module Az.Accounts
#Requires -Module Az.Resources
#Requires -Module Az.Storage




<#
 
.DESCRIPTION
Remove Unattached Disks from Azure subscription
 
#>
 

Param()


Workflow Remove-UnattachedDisks
{ 
    Param 
    (    
        [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] 
        [String] 
        $AzureSubscriptionId="<Your Subscription ID>", 
                
        # Set deleteUnattachedManagedDisks=1 if you want to delete unattached Managed Disks
        # Set deleteUnattachedManagedDisks=0 if you want to see the Id of the unattached Managed Disks
        
        [Parameter(Mandatory=$true)][ValidateSet("True","False")]
        [String] 
        $deleteUnattachedManagedDisks, 

         # Set deleteUnattachedVHDs=$true if you want to delete unattached VHDs
         # Set deleteUnattachedVHDs=$false if you want to see the Uri of the unattached VHDs

        [Parameter(Mandatory=$true)][ValidateSet("True","False")]
        [String] 
        $deleteUnattachedVHDs
    ) 

    

    $connectionName = "AzureRunAsConnection"

    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    
    Connect-AzAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 

        select-azsubscription -subscriptionid $AzureSubscriptionId
    


                 
                                
                                $deleteUnattachedManagedDisks=0

                                $managedDisks = Get-AzDisk
                               
                                ForEach ($md in $managedDisks) {
                                 
                                    
                                    # ManagedBy property stores the Id of the VM to which Managed Disk is attached to
                                    # If ManagedBy property is $null then it means that the Managed Disk is not attached to a VM
                                    if($md.ManagedBy -eq $null){
                                        if($deleteUnattachedManagedDisks -eq "True"){
                                            #Write-Host "Deleting unattached Managed Disk with Id: $($md.Id)"
                                            $md | Remove-AzDisk -Force
                                            #Write-Host "Deleted unattached Managed Disk with Id: $($md.Id) "
                                        }else{
                                            $md.Id
                                        }
                                    }
                                 
                                }
                                
                                Checkpoint-Workflow
                               

                              InlineScript {
                               
                                $storageAccounts =  Get-AzStorageAccount
                                ForEach($storageAccount in $storageAccounts){
                                    #Write-Host $storageAccount
                                    $storageKey = (Get-AzStorageAccountKey -ResourceGroupName $storageAccount.ResourceGroupName -Name $storageAccount.StorageAccountName)[0].Value
                                    $context = New-AzStorageContext -StorageAccountName $storageAccount.StorageAccountName -StorageAccountKey $storageKey
                                    $containers = Get-AzStorageContainer -Context $context
                                    foreach($container in $containers){
                                        $blobs = Get-AzStorageBlob -Container $container.Name -Context $context
                                        #Fetch all the Page blobs with extension .vhd as only Page blobs can be attached as disk to Azure VMs
                                        $blobs | Where-Object {$_.BlobType -eq 'PageBlob' -and $_.Name.EndsWith('.vhd')} | ForEach-Object { 
                                            #If a Page blob is not attached as disk then LeaseStatus will be unlocked
                                            if($_.ICloudBlob.Properties.LeaseStatus -eq 'Unlocked'){
                                                    if($deleteUnattachedVHDs -ne "False"){
                                                       
                                                        $_ | Remove-AzStorageBlob -Force
                                                       
                                                    }
                                                    else{
                                                        $_.ICloudBlob.Uri.AbsoluteUri
                                                    }
                                               }
                                            }
                                       }
                                   } 
                               }                     
                          
        }