I am writing a query to capture azure virtual machine disk details and saving it in array. This VM has two disks. Unfortunately my array is overwritten by the second disk. i.e., Details of the second disk is appearing twice instead of each lines for each disks.
$t = @()
$array =@()
foreach ($disk in $r.storageProfile.DataDisks.Name) {
$t= Get-AzDisk -ResourceGroupName $ResourceGroupName -DiskName $disk
$ReportDetails.VMName = $r.Name
$ReportDetails.DiskName = $t.Name
$ReportDetails.DiskSizeGB= $t.DiskSizeGB
$ReportDetails.sku= $t.Sku.Name
$ReportDetails.Lun= ($r.storageProfile.DataDisks | Where-Object -filterscript {$_.Name -eq $disk}).lun
$ReportDetails.Caching= ($r.storageProfile.DataDisks | Where-Object -filterscript {$_.Name -eq $disk}).Caching
$ReportDetails.DiskIOPSReadWrite= $t.DiskIOPSReadWrite
$ReportDetails.DiskMBpsReadWrite = $t.DiskMBpsReadWrite
$ReportDetails
$array += $ReportDetails
}
$array | Out-GridView
When I print the value of $ReportDetails. it appears properly with correct data during two iterations.
However array() is showing second disk twice.
$ReportDetails?$ReportDetails, is probably an object where each property references to a value (which you overwrite with each iteration). As a general best practice, I recommend you to avoid using the increase assignment operator (+=) to create a collection and use the pipeline to build the$arrayas lined out in the referal.