Azure Azure Cost Management Azure PowerShell

Azure Cloud Sp€nd: Get the start date, end date and current cost for the current billing period of all Subscriptions in a Tenant with Azure PowerShell


This blog post will show you how you can get the start date, end date and the current cost for the current billing period of all subscriptions in a tenant with the use of an Azure PowerShell script.

With Azure Cost Management (Cost Management + Billing), Microsoft provides a good way to analyze, report, optimize and to keep control of your Azure cloud costs (cloud spend).

Next to the Azure Portal, Azure CLI or Biceps, you can also use Azure PowerShell cmdlets to manage Azure Billing and to perform cost related tasks. For this type of management and operations Azure PowerShell uses the Az.Billing module, currently version 2.0.0.


With the use of the available cmdlets in this module it is quiet easy to get for example the billing periods of a specific subscription (Get-AzBillingPeriod) or to get the usage details of that subscription (Get-AzConsumptionUsageDetail). Of course like with all other cmdlets you can use them separately or combine them in a script.

Because a lot of Azure environments these days combine different tenants with multiple subscriptions, I wrote the below Azure PowerShell script, to quickly get some specific cost information details about an environment.

The script gets the start date, end date and the current cost for the current billing period and this for all subscriptions in a tenant. For this, I used some of the Az.Billing cmdlets in the script to do all of the following:

  • Suppress breaking change warning messages.
  • Loop trough all subscriptions in the current tenant (if you do not specify the tenant before running the script this will be the default tenant).
  • Get the current billing period start date for each subscription in the tenant.
  • Get the current billing period end date for each subscription in the tenant.
  • Get the current billing period current cost for each subscription in the tenant. Also catch if the current cost is € 0 or $ 0, and when Cost Management is not supported for the subscription (type).

When using the script, keep in mind that the script will work with all types of Azure Subscriptions (Enterprise Agreement, Pay-as-you-Go, Visual Studio Enterprise, MSDN subscriptions, …), except with CSP subscriptions because those are using a different API for cost management (Cost Management for CSP). Next to that, a sponsored Azure subscription will not show the cost for the current billing period, but will display “Cost Management is not supported for the subscription (type)”.


To use the script copy and save it as Get-Current-BillingPeriod-StartDate-EndDate-and-CurrentCost-for-all-Subscriptions-in-Tenant.ps1 or download it from GitHub. Then run the script from Windows TerminalVisual Studio Code, or Windows PowerShell. Or you can simply run it from Cloud Shell.


Prerequisites

  • An Azure subscription.
  • An Azure Administrator account with the necessary RBAC roles
  • When running from PowerShell -> Azure Az PowerShell module: Install-Module Az
  • When running from PowerShell -> Az.Billing module: Install-Module Az.billing


Azure PowerShell script

If you are not running the script from Cloud Shell, don’t forget to sign in with the Connect-AzAccount cmdlet to connect your Azure account. And if you have multiple tenants, select the proper tenant with the Set-AzContext -tenantID “xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx” cmdlet before running the script. You can list all tenants for the current user with the Get-AzTenant cmdlet.


<#
.SYNOPSIS

A script used to get the start date, the end date and het current cost for the current billing period of all subscriptions in a tenant.

.DESCRIPTION

A script used to get the start date, the end date and het current cost for the current billing period of all subscriptions in a tenant.
First of all the script will get the start date for the current billing period.
Then it will get the end date for the current billing period. 
And finally it will calculate the current cost for the current billing period.
All of the above will be displayed per subscription in the tenant.

The script will work with all types of Azure Subscriptions (EA, Pay-as-you-Go, Visual Studio Enterprise, MSDN subscriptions, …), except with CSP subscriptions.

.NOTES

Filename:       Get-Current-BillingPeriod-StartDate-EndDate-and-CurrentCost-for-all-Subscriptions-in-Tenant.ps1
Created:        26/01/2022
Last modified:  26/01/2022
Author:         Wim Matthyssen
PowerShell:     Azure Cloud Shell or Azure PowerShell
Version:        Install latest Azure PowerShell modules (at least Az version 7.1.0 and Az.Billing version 2.0.0 is required)
Action:         Change variables were needed to fit your needs. 
Disclaimer:     This script is provided "As Is" with no warranties.

.EXAMPLE

Connect-AzAccount
Get-AzTenant (if not using the default tenant)
Set-AzContext -tenantID "xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx" (if not using the default tenant)
.\Get-Current-BillingPeriod-StartDate-EndDate-and-CurrentCost-for-all-Subscriptions-in-Tenant.ps1

.LINK

https://wmatthyssen.com/2022/01/27/azure-cloud-spend-get-the-start-date-end-date-and-current-cost-for-the-current-billing-period-of-all-subscriptions-in-a-tenant-with-azure-powershell/
#>

## ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Variables

$global:currenttime= Set-PSBreakpoint -Variable currenttime -Mode Read -Action {$global:currenttime= Get-Date -UFormat "%A %m/%d/%Y %R"}
$foregroundColor1 = "Red"
$foregroundColor2 = "Yellow"
$writeEmptyLine = "`n"
$writeSeperatorSpaces = " - "

## ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Suppress breaking change warning messages

Set-Item Env:\SuppressAzurePowerShellBreakingChangeWarnings "true"

## ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Start script execution

Write-Host ($writeEmptyLine + "# Script started. Depending on the amount of subscriptions, it will need around 1 - 2  minute(s) to complete" + $writeSeperatorSpaces + $currentTime)`
-foregroundcolor $foregroundColor1 $writeEmptyLine 
 
## ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Get start date, end date and current cost

# Loop trough all subscriptions in tenant and run commands
$subscriptions = Get-AzSubscription
foreach ($sub in $subscriptions)
{
    $sub | Select-AzSubscription
    
    $currentBillingPeriod = Get-AzBillingPeriod -MaxCount 1
    
    # Get start date
    $startDate = $currentBillingPeriod.BillingPeriodStartDate.ToString("yyyy-MM-dd")
    Write-Host ($writeEmptyLine + "# Current billing period start date: " + $startDate)`
    -foregroundcolor $foregroundColor2  

    # Get end date
    $endDate = $currentBillingPeriod.BillingPeriodEndDate.ToString("yyyy-MM-dd")
    Write-Host ($writeEmptyLine + "# Current billing period end date: " + $endDate)`
    -foregroundcolor $foregroundColor2 

    # Get current cost
    try 
    {
        $found = Get-AzConsumptionUsageDetail -StartDate $startDate -EndDate $endDate -ea 0
    
        if ($found.PretaxCost){
            $currentCost = $found | Measure-Object -Property PretaxCost -Sum
            Write-Host ($writeEmptyLine + "# Current Cost of Subscription: " + $currentCost.Sum)`
            -foregroundcolor $foregroundColor2 $writeEmptyLine
        } else {
            $msg = $writeEmptyLine + "# Current Cost of Subscription: 0 or Cost Management is not supported for the subscription (type) with Subscription ID: {0}" -f $sub.ToString() 
            Write-Host $msg -foregroundcolor $foregroundColor1 $writeEmptyLine
        }
    } catch {
        $msg="Error: {0}" -f $sub.ToString() ; Write-Host $msg -foregroundcolor $foregroundColor2 $writeEmptyLine 
    }  
}  

## ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Write script completed

Write-Host ($writeEmptyLine + "# Script completed" + $writeSeperatorSpaces + $currentTime)`
-foregroundcolor $foregroundColor1 $writeEmptyLine 

## ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



I hope this Azure PowerShell script is useful for you and helps you with managing and controlling your Azure Cloud Sp€nd.

If you have any questions or recommendations about it, feel free to contact me through my Twitter handle (@wmatthyssen) or to just leave a comment.


0 comments on “Azure Cloud Sp€nd: Get the start date, end date and current cost for the current billing period of all Subscriptions in a Tenant with Azure PowerShell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: