Search code examples
powershellazurecsvexport-csv

powershell export-csv sum column per each row


I wrote this script to output a table formatted file:

$VMs = Get-AzureRmVM
$vmOutput = $VMs | ForEach-Object { 
    [PSCustomObject]@{
        "VM Name" = $_.Name
        "VM Type" = $_.StorageProfile.osDisk.osType
        "VM Profile" = $_.HardwareProfile.VmSize
        "VM OS Disk Size" = $_.StorageProfile.OsDisk.DiskSizeGB
        "VM Data Disk Size" = ($_.StorageProfile.DataDisks.DiskSizeGB) -join ','
    }
}

$vmOutput  | export-csv C:\***\data.csv -delimiter ";" -force -notypeinformation 

Is there any possibility to sum "VM Data Disk Size" for each object? I used -join parameter only because data wasn't properly exported, because of more than one data disk per vm.


Solution

  • if you have an array of numbers and you want to sum them use:

    ($NumArray | Measure -Sum).Sum

    in your case it would be:

    "VM Data Disk Size" = ($_.StorageProfile.DataDisks.DiskSizeGB | Measure -Sum).Sum

    Measure is an alias for Measure-Object if you're looking for the help pages or anything, it can also do Average, Min/Max etc.