NonAttachedManagedDisk.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#requires -Version 5
#requires -Modules @{ ModuleName='AzureRM.Profile'; ModuleVersion='2.6.0' }
#requires -Modules @{ ModuleName='AzureRM.Compute'; ModuleVersion='2.7.0' }

<#
.SYNOPSIS
Get the managed disks that non-attached to any virtual machines from the entire subscription.
 
.DESCRIPTION
Get the managed disks that non-attached to any virtual machines from the entire subscription.
 
.PARAMETER ExcludeResourceGroup
This cmdlet is ignore the resource groups that provided by this parameter. This parameter is optional.
 
.EXAMPLE
    Get-AzureUtilNonAttachedManagedDisk
 
In this example, it is to get the all non-attached managed disk resources in the current subscription.
 
.EXAMPLE
    Get-AzureUtilNonAttachedManagedDisk -ExcludeResourceGroup 'Prod-RG','Test-RG'
 
In this example, it is to get the all non-attached managed disk resources in the current subscription except the disk resources in the "Prod-RG" and "Test-RG" resource groups.
 
.EXAMPLE
    Get-AzureUtilNonAttachedManagedDisk | Remove-AzureRmDisk -Verbose
 
In this example, it is to remove the all non-attached managed disk resources in the current subscription.
 
.LINK
PowerShell Gallery: https://www.powershellgallery.com/packages/AzureUtil/
 
.LINK
GitHub: https://github.com/tksh164/AzureUtil-PowerShellModule
 
.LINK
Get-AzureUtilNonAttachedUnmanagedDisk
 
.LINK
Get-AzureUtilEmptyResourceGroup
#>

function Get-AzureUtilNonAttachedManagedDisk
{
    [CmdletBinding()]
    [OutputType([Microsoft.Azure.Commands.Compute.Automation.Models.PSDiskList])]
    param (
        [Parameter(Mandatory = $false)][ValidateNotNullOrEmpty()]
        [string[]] $ExcludeResourceGroup
    )

    # Login check.
    try { [void] (Get-AzureRMContext -ErrorAction Stop) } catch { throw }

    # List non-attached managed disks.
    (Get-AzureRmDisk).ToArray() |
        Where-Object -FilterScript {
            ($ExcludeResourceGroup -notcontains $_.ResourceGroupName) -and ($_.OwnerId -eq $null)
        }
}