Azuer VM cost via PowerShell

Oleg Aronov 106 Reputation points
2019-12-06T16:24:09.407+00:00

Hello:

I'd like to be able to find VM cost for some period via PowerShell script.
Is it possible?

I thought I should be able to get it via " Get-AzConsumptionUsageDetail", but it gives me number(s) not even close to what I see in portal (6x or even 10x times difference).

Here is my script:

$Consumption = Get-AzConsumptionUsageDetail -ResourceGroup $RGName -StartDate $StartDay -EndDate $EndDay -InstanceName $VMName
$Costs = $Consumption.UsageQuantity
foreach ($Cost in $Costs) { $CostTotal += $Cost}

$CostTotal is my final number.

What am I doing wrong?
Is it possible to get VM cost for some (past) period via PowerShell script?

Thank you!

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
7,185 questions
0 comments No comments
{count} votes

Accepted answer
  1. msrini-MSFT 9,261 Reputation points Microsoft Employee
    2019-12-06T18:39:46.323+00:00

    Hi,

    Your PS script is perfect. But you made one mistake. You have calculated the UseageQunatity instead of the Pretax Cost.

    here is the script which will give you the exact cost :

    $costTotal=0  
    $RGName ="RGNAME"   
    $StartDay="2019-12-01"  
    $EndDay="2019-12-06"  
    $VMName="vm1"  
    $Consumption = Get-AzConsumptionUsageDetail -ResourceGroup $RGName -StartDate   
    $StartDay -EndDate $EndDay -InstanceName $VMName   
      
    $Costs = $Consumption.PretaxCost  
      
    foreach ($Cost in $Costs) { $CostTotal += $Cost}  
      
    $CostTotal  
    
    3 people found this answer helpful.

0 additional answers

Sort by: Most helpful