azurepowershellazure-powershellsubscription

How to get the azure subscription current cost using PowerShell


I am trying to get my azure subscription current cost using PowerShell. enter image description here

Desired Output:

e.g:

currency = GBP

current cost = 370.74

Get-AzConsumptionUsageDetail -BillingPeriodName 202105

But this does not give me the desired output.


Solution

  • The below query will give you the cost of the mentioned month. e.g: cost of May month

    Get-AzConsumptionUsageDetail -BillingPeriodName 202105
    

    But if your subscription does not start with the 1st of May then in this case the above query will give you the wrong cost. e.g: your billing cycle is from 10 May to 09 June

    To know the cost of your exact billing cycle you need to get the current billing period first and then get the cost based on billing cycle start/end date.

    $currentBillingPeriod = Get-AzBillingPeriod -MaxCount 1
    $startDate = $currentBillingPeriod.BillingPeriodStartDate.ToString("dd-MM-yyyy")
    Write-Host "currentBillingPeriod startDate : " $startDate
    $endDate = $currentBillingPeriod.BillingPeriodEndDate.ToString("dd-MM-yyyy")
    Write-Host "currentBillingPeriod endDate : " $endDate
    
    $currentCost = Get-AzConsumptionUsageDetail -StartDate $startDate -EndDate $endDate | Measure-Object -Property PretaxCost -Sum
    Write-Host "Current Cost of Subscription : " $currentCost.Sum