Skip to content

Instantly share code, notes, and snippets.

@northtyphoon
Last active April 10, 2023 05:37
Show Gist options
  • Save northtyphoon/18bfa37e1d459c9916d4f7fce5481531 to your computer and use it in GitHub Desktop.
Save northtyphoon/18bfa37e1d459c9916d4f7fce5481531 to your computer and use it in GitHub Desktop.

Powershell script to get total compute (vmss and vm) usage (vm and core count)

<#
.SYNOPSIS
    Get Compute Usage (VMSS + VM) and output the details in CSV format to compute-usage.csv file
 
.EXAMPLE
    .\GetComputeUsage.ps1 -targetSubscriptionName "My Subscription Name"
#>

[CmdletBinding()]
Param(
    [Parameter(Mandatory = $false)]
    [string] $targetSubscriptionName = ""
)

$result = @()

Login-AzAccount

$subscriptions = Get-AzSubscription

$count = $subscriptions.Count

Write-Host "Found total subscription count: $count"

foreach ($subscription in $subscriptions) {
    $subscriptionName = $subscription.Name

    if ($targetSubscriptionName -ne "" -and $targetSubscriptionName -ne $subscriptionName) {
        
        Write-Host ""
        Write-Host "Skip $subscriptionName as it is not $targetSubscriptionName"
        continue
    }

    Write-Host ""
    Select-AzSubscription $subscription.Id
    
    $vmssList = Get-AzVmss

    foreach ($vmss in $vmssList) {

        $sku = Get-AzVMSize -Location $vmss.Location | where {$_.Name -eq $vmss.Sku.Name}

        $resource = New-Object PsObject -Property @{"Subscription"=$subscriptionName; "Location"=$vmss.Location; "ResourceGroup"=$vmss.ResourceGroupName; "Name"=$vmss.Name; "Sku"=$vmss.Sku.Name; "VmCount"=$vmss.Sku.Capacity; "CoreCount"=$sku.NumberOfCores}

        $resource | ConvertTo-Csv

        $result += $resource
    }

    $vmList = Get-AzVM

    foreach ($vm in $vmList) {
        
        $sku = Get-AzVMSize -Location $vm.Location | where {$_.Name -eq $vm.HardwareProfile.VmSize}

        $resource = New-Object PsObject -Property @{"Subscription"=$subscriptionName; "Location"=$vm.Location; "ResourceGroup"=$vm.ResourceGroupName; "Name"=$vm.Name; "Sku"=$vm.HardwareProfile.VmSize; "VmCount"=1; "CoreCount"=$sku.NumberOfCores}

        $resource | ConvertTo-Csv

        $result += $resource
    }

    $result | Export-Csv compute-usage.csv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment