Azuer VM cost via PowerShell

olegarr 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.
4,595 questions
No comments
{count} votes

Accepted answer
  1. msrini-MSFT 5,676 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  
    

0 additional answers

Sort by: Most helpful