Skip to content

Instantly share code, notes, and snippets.

@mmckechney
Last active April 10, 2020 12:26
Show Gist options
  • Save mmckechney/108c91b1c9bbc7eb4db7553453c12d78 to your computer and use it in GitHub Desktop.
Save mmckechney/108c91b1c9bbc7eb4db7553453c12d78 to your computer and use it in GitHub Desktop.
Collect Storage Account Usage Metrics

Intro:

This PowerShell script will collect usage information on all of the storage accounts you have access to as well as getting their location and SKU. It will output in a table format

How to use

First, you will need to install the ARMClient.exe application. This is what makes the REST calls to the the metrics APIs.

You can download and install from here:https://github.com/projectkudu/ARMClient/releases and extract the Zip

To run the script

  1. Download the PowerShell script into the same directory as you extracted the ARMClient.exe
  2. In a PowerShell console window: Run .\ARMClient.exe login to login the metrics APIs
  3. Run Connect-AzAccount to login to Azure PowerShell
  4. Run .\StorageAccountsUsageMetrics.ps1 this will iterate through all of the subscriptions you have access, then get metrics on all of the storage accounts.
## Get storage accounts usage metrics
# Connect-AzAccount
#.\ARMClient.exe login
$accountUsage = @()
class ByteUsage {
[string]$subscription
[string]$resourceGroupName
[string]$storageAccountName
[string]$location
[string]$SKU
[Int64]$bytes
[double]$Gb
}
$allSubs = Get-AzSubscription
Write-Output $allSubs | Format-Table -AutoSize
for($i = 0; $i -lt $allSubs.length; $i++)
{
#Force context to the current subscription
Remove-AzContext -InputObject (Get-AzContext) -Force | Out-Null;
$ctx = Set-AzContext -SubscriptionObject $allSubs[$i]
Write-Output $ctx | Format-Table -AutoSize
$subId = $ctx.Subscription.Id
$subName = $ctx.Subscription.Name
#Get All of the storage accounts for the current subscription
$sa = Get-AzStorageAccount
#Loop through and get the usage metrics per storage account
foreach($a in $sa)
{
Write-Output $a.StorageAccountName
$rg = $a.ResourceGroupName
$saName = $a.StorageAccountName
$saLocation = $a.Location
$saSku = $a.Sku.Name
$resourcePath = "/subscriptions/$subId/resourceGroups/$rg/providers/Microsoft.Storage/storageAccounts/$saName/providers/microsoft.insights/metrics?metricnames=UsedCapacity&api-version=2018-01-01&aggregation=Average&interval=PT1H"
#make the metrics call
$output = (.\ARMClient.exe GET $resourcePath) -join " "
$json = $output | ConvertFrom-Json
$tmpUsage = [ByteUsage]@{subscription= $subName;
storageAccountName = $saName;
resourceGroupName = $rg;
location = $saLocation
SKU = $saSku
bytes = $json.value.timeseries.data.average;
gb = [math]::Round($json.value.timeseries.data.average/1000000000, 3)}
$accountUsage += $tmpUsage
}
}
#output results
$accountUsage | Format-Table -AutoSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment