0

I am attempting to query Azure Cost Management to query usage for two different dates each for two different resource groups. The value I am trying to query are:

  1. The current month total usage
  2. The previous month total usage (relative to the current date), so if today were the 5th, it would query for cost up until the 5th of the previous month.

I keep having null values returned by the API. At first, I thought this may just be because today is 04/01 (the start of a new month)... but no matter how I adjust the timeframe, the result does not seem to change. How do I use Invoke-AzCostManagementQuery to execute a custom query like this?

    $prev_month_same_day = (Get-Date).AddMonths(-1).AddDays(-1)
    $first_of_prev_month = [DateTime]::ParseExact(($prev_month_same_day | Get-Date -Format "MM/01/yyyy"), 'MM/dd/yyyy', $null)

    $scope_managed_rg = "/subscriptions/" + $subscription_id + "/resourceGroups/" + $db_managed_rg
    $scope_unmanaged_rg = "/subscriptions/" + $subscription_id + "/resourceGroups/" + $db_unmanaged_rg

    $rg1_currMonthRaw = Invoke-AzCostManagementQuery -Type "Usage" -scope $scope_managed_rg -timeframe "MonthToDate"
    $rg2_currMonthRaw = Invoke-AzCostManagementQuery -Type "Usage" -scope $scope_unmanaged_rg -timeframe "MonthToDate"
    $rg1_prevMonthRaw = Invoke-AzCostManagementQuery -Type "Usage" -scope $scope_managed_rg -TimePeriodFrom $first_of_prev_month -TimePeriodTo $prev_month_same_day -Timeframe "Custom"
    $rg2_prevMonthRaw = Invoke-AzCostManagementQuery -Type "Usage" -scope $scope_unmanaged_rg -TimePeriodFrom $first_of_prev_month -TimePeriodTo $prev_month_same_day -Timeframe "Custom"
Ken
  • 53
  • 6
  • You say that you want the _same_ day, but you're using `.AddDays(-1)`. If you want the same day, but the _very start_ of that day, use `$prev_month_same_day = (Get-Date).AddMonths(-1).Date`. With today's date, your current approach makes you query _February_, whereas the proposed approach queries _March_. You can avoid string parsing by calculating the other date as follows: `$first_of_prev_month = [DateTime]::new($prev_month_same_day.Year, $prev_month_same_day.Month, 1)` Apart from that, it's not obvious wha the problem is. – mklement0 Apr 01 '23 at 16:08
  • Good catch. I threw that day modifier in at the last second because I wanted to know if it was the End of Month that was messing up my query. lol Apart from that, though, I still continue to get null values whenever I make a query. Regardless of the actual parameters I provide. – Ken Apr 04 '23 at 06:14

1 Answers1

1

Try following :

$today = [DateTime]::Now
$month = $today.Month
$year = $today.Year
$day = $today.Day
if($month -eq 1)
{
   $year -= 1
   $month = 12
} else
{
   $month -= 1
}
$lastMonth = [DateTime]::New($year, $month, $day)
$lastMonth
jdweng
  • 33,250
  • 2
  • 15
  • 20