Search Unused Resource in Azure using CLI

Hi. sometimes, we forgot delete unused resource.
It cause only delete Azure VM not include attached resource such as disk, nic, nsg, public Ip.
Especially, you have over 100 resource in subscription… it’s hard to check it.
But, if you use CLI in this post, you can easy find it.

Search unattached managed disk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
write-host 'no associated disk searching...'
$results = @()
$diskList = az disk list | convertFrom-Json
$results += $diskList | foreach-object -parallel {
if(!$_.managedBy) {
$noDisk = $_.id -split "/"
$details = @{
rgName=$noDisk[4]
noAttachedDisk=$noDisk[8]
}
return New-Object PSObject -Property $details
}
}
write-host ($results | select-object rgName, noAttachedDisk | Sort-Object { $_.rgName} | format-table | Out-String) -ForegroundColor Red

No Associated Public IP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
write-host 'no associated ip searching...'
$results = @()
$ipList = az network public-ip list | convertFrom-Json
$results += $ipList | foreach-object -parallel {
if(!$_.ipConfiguration) {
$noIp = $_.id -split "/"
#write-host $noIp[4] : $noIp[8] -ForegroundColor Red
$details = @{
rgName=$noIp[4]
noAssocatedIP=$noIp[8]
}
return New-Object PSObject -Property $details
}
}
write-host ( $results | select-object rgName, noAssocatedIp | Sort-Object { $_.rgName} | format-table | out-string ) -ForegroundColor Red

No Associated NiC to VM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
write-host 'no associated nic searching...'
$results= @()
$nicList = az network nic list | convertFrom-Json
$results += $nicList | foreach-object -parallel {
if(!$_.virtualMachine) {
$noNic = $_.id -split "/"
$details = @{
rgName=$noNic[4]
noAttachedNic=$noNic[8]
}
return New-Object PSObject -Property $details
}
}
write-host ( $results | select-object rgName, noAttachedNic | Sort-Object { $_.rgName} | format-table | out-string ) -ForegroundColor Red

No Associated NSG

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
write-host 'no assocated nsg searching...'
$results = @()
$nsgList = az network nsg list | convertFrom-Json
$results += $nsgList | foreach-object -Parallel {
$rtnNsg = Get-AzNetworkSecurityGroup -name $_.name
if(!$rtnNsg.NetworkInterfaces -and !$rtnNsg.Subnets) {
$noNsg = $_.id -split "/"
$details = @{
rgName=$noNsg[4]
noAssocatedNsg=$noNsg[8]
}
return New-Object PSObject -Property $details
}
} -ThrottleLimit 20
write-host ( $results | select-object rgName, noAssocatedNsg | Sort-Object { $_.rgName} | format-table | out-string ) -ForegroundColor Red
Share