$bullingPeriodStartDay = "06" #Start day bulling period $clientid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" $clientsecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" $subscriptionid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" $tenantid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" $resource = "https://management.azure.com/" $tokenendpoint = "https://login.microsoftonline.com/$tenantid/oauth2/token" $body = @{ grant_type = "client_credentials" resource = $resource client_id = $clientid client_secret = $clientsecret } $tokenresponse = Invoke-RestMethod -Method Post -Uri $tokenendpoint -Body $body -ContentType "application/x-www-form-urlencoded" $accesstoken = $tokenresponse.access_token $headers = @{ 'Authorization' = "Bearer $accesstoken" 'Content-Type' = 'application/json' } $bullingPeriodToday = (get-date -format "dd") if ([int]$bullingPeriodToday -ge [int]$bullingPeriodStartDay) { $bullingPeriodCurrentStart = (Get-Date -format "yyyy-MM-$bullingPeriodStartDay") $bullingPeriod = (Get-Date((get-date).AddDays(30)) -format "yyyyMM") } else { $bullingPeriodCurrentStart = (Get-Date((get-date).AddDays(30)) -format "yyyy-MM-$bullingPeriodStartDay") $bullingPeriod = (get-date -format "yyyyMM") } $dateEnd = Get-Date $dateEnd = (Get-Date).ToString("s") $dateStart = $bullingPeriodCurrentStart + "T00:00:00.0000000Z" $requesturi = "https://management.azure.com/subscriptions/$subscriptionid/providers/Microsoft.Billing/billingPeriods/$bullingPeriod/providers/Microsoft.Consumption/usageDetails?api-version=2019-01-01&$filter=properties/usageStart ge '$dateStart' and properties/usageEnd le '$dateEnd'" $ret = (Invoke-RestMethod -Uri $requesturi -Headers $headers -Method Get) $usageCost = $ret.value.properties.pretaxCost|measure-object -Sum $usageCost = [Math]::Round($usageCost.Sum) Write-Output $usageCost