Are you chased by your finance department to give them the invoices of all of your Azure subscriptions? The answer “You can download them from the portal…” is not enough for them? Here is a tool that can help both you and them.
Use PowerShell to download all your invoices! Microsoft.Azure.Commands.Billing namespace is your friend. The Get-AzureRmBillingInvoice has a parameter -GenerateDownloadUrl that does what it’s name suggests. What else you need? The System.Net.WebClient has a DownloadFile method, so all we need is to create the overhead code around these.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# Download invoices from Azure using PowerShell # Signing in Write-Host "Logging in..."; Login-AzureRmAccount #These are for info only $startTime = Get-Date $newInvoice=0 $oldInvoice=0 # Let's go through all subscriptions you have access to foreach($subscription in Get-AzureRmSubscription) { Set-AzureRmContext -SubscriptionId $subscription.SubscriptionId Write-Host "Subscription Name:$($subscription.Name) - Tenant ID: $($subscription.TenantId)" #Change -MaxCount if you want to download more than 10 (months) Foreach($invoice in Get-AzureRmBillingInvoice -GenerateDownloadUrl -MaxCount 10) { # The filename will start with the invoice name concanated with the subscription ID $output="D:\\Azure\\Invoices\\$($invoice.Name)-$($subscription.ID).pdf" $url = $invoice.DownloadURL if(!($url)) { Write-Host "URL is not valid for $($invoice.Name)-$($subscription.ID).pdf from $($url)" } else { if(![System.IO.File]::Exists($output)){ Write-Host "Downloading $($invoice.Name)-$($subscription.ID).pdf from $($url)" $webClient = New-Object System.Net.WebClient $webClient.DownloadFile($url, $output) Write-Host "Download result: $($webClient.DownloadFileCompleted)" $newInvoice++ } else { Write-Host ">>> $($output) has been dowloaded earlier." $oldInvoice++ } } } } Write-Host "$($newInvoice) new invoices have been downloaded, $($oldInvoice) were here already." Write-Output "Time taken: $((Get-Date).Subtract($startTime).Seconds) second(s)" |
If you receive WARNING: You are not allowed to download invoices. Please contact your account administrator (username@companyname.com) to turn on access in the management portal for allowing to download invoices through the API. error message, please ask the owner of the Subscription to enable “Access to invoice”.