azurepowershellazure-powershell

PowerShell to list all Azure VM data disk size confusion


Based on this KB article from Microsoft Azure: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/faq#how-much-storage-can-i-use-with-a-virtual-machine-

We can attach multiple Data disks to Azure VM.

However, how can we show it in the PowerShell query dynamically ?

Get-AzVM | ForEach-Object {
    $size = $_.HardwareProfile.VmSize
    $vmsize = Get-AzVMSize -vmname $_.Name -ResourceGroupName $_.ResourceGroupName | Where-Object { $_.name -eq $size }
    $nic = $_.NetworkProfile.NetworkInterfaces.id.split('/') | Select-Object -Last 1

    # Implicitly outputs an object with the given properties
    [pscustomobject]@{
        Location   = $_.Location
        Name       = $_.Name
        osdiskingb = $_.StorageProfile.OsDisk.DiskSizeGB
        data1diskingb = ($_.StorageProfile.DataDisks[0].DiskSizeGB)
        data2diskingb = ($_.StorageProfile.DataDisks[1].DiskSizeGB)
        data3diskingb = ($_.StorageProfile.DataDisks[2].DiskSizeGB)
        memory     = [Math]::Round(($vmsize.MemoryInMB)/1024, 1)
        cpu        = $vmsize.NumberOfCores
        nic        = $nic
        ip         = (Get-AzNetworkInterface -Name $nic).ipconfigurations.privateipaddress
        VMTags     = $_.Tags
        VMStatus   = $_.StatusCode
        State      = $_.ProvisioningState
    } 
} | ogv

Using the above static PowerShell query created by Zett42 from: Optimize PowerShell code to avoid calling the cmdlet multiple times inside calculated properties? I can only manually copy paste/repeats this line below:

data1diskingb = ($_.StorageProfile.DataDisks[0].DiskSizeGB)
data2diskingb = ($_.StorageProfile.DataDisks[1].DiskSizeGB)
data3diskingb = ($_.StorageProfile.DataDisks[2].DiskSizeGB)

If the Azure VM has more than 5-10 data disks, I must copy and paste it accordingly multiple times.

So I need to update the script so it can show all Data Disk dynamically.


Solution

  • $vm                 = Get-AzVM -Name <VM-Name> -ResourceGroupName <RG-Name>
    $os_disk_size       = $vm.StorageProfile.OsDisk.DiskSizeGB
    $total_disk_size    = 0
    $data_disk_size     = 0
    $data_disks         = (Get-AzVM -Name $vm_name).StorageProfile.DataDisks
    foreach ($data_disk in $data_disks) {
        $data_disk_size     = $data_disk_size + $data_disk.DiskSizeGB
    }
    $total_disk_size    = $os_disk_size + $data_disk_size
    Write-Host "OS Disk size in GB: $os_disk_size"
    Write-Host "Total Data disk($data_disks.count) size in GB: $data_disk_size"
    Write-Host "Total disk size allocated to $vm.name: $total_disk_size"
    

    You should be able to get a lot of details from this.