Azure provides a good way with Cost Management to report the costs and consumption of Azure Services. It offers various filtering, aggregation and export options. In some cases, however, it is still necessary to call up and process the data via script. I would like to briefly show the cost export with PowerShell and the use of the very useful functions Group and Measure.

The following script exports costs and sums up the costs per day per ResourceGroup of the last days.

$costs = Get-AzConsumptionUsageDetail -StartDate (Get-Date).AddDays(-2) -EndDate (Get-Date).AddDays(-1)
$costs | % { Add-Member -InputObject $_ -NotePropertyName Selector -NotePropertyValue ($_.InstanceId.split('/')[2]+">"+$_.InstanceId.split('/')[4]).ToLower() }
$groups = $costs | Group -Property 'Selector', 'UsageStart'
$groups | % { New-Object psobject -Property @{ Id=$_.Values[0]; Date=$_.Values[1]; Sum=($_.Group  | Measure -Property 'PretaxCost' -Sum).Sum } }

Line 1 gets the consumption and costs. The output from Get-AzConsumptionUsageDetail lists all resources with all consumption per day. For example, if a Storage Account has caused storage costs and data transfer costs, the same resource is listed twice with the respective individual costs.

In order to summarize the data per resource or resource group (like in the script), this can be done with Group. The properties that should to be unique are specified as the property, i.e. similar to having in SQL. Line 2 adds a new property selector, it combines the subscription ID and the name of the resource group (a resource group is only unique within a subscription). Then the grouping is based on this property and the day of usage (line 3). The resulting groups contain values ​​that represent the unique grouping properties and groups that contain the grouped objects.

Line 4 sums up each group. To do this, a new object is created that contains the first (unique selector) and the second (usage date) group values ​​as properties. The third property is the sum of the PretaxCost property, generated with Measure and made up of all the objects in the group.