0

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.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
Arun C O
  • 35
  • 4
  • 3
    What is `$ReportDetails` ? – Santiago Squarzon Dec 23 '22 at 01:54
  • 1
    As the question from Santiago implies, `$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](https://stackoverflow.com/a/60708579/1701026) and use the pipeline to build the `$array` as lined out in the referal. – iRon Dec 23 '22 at 08:13
  • ReportDetails is a class object which is ByRef (not ByValue) so there is only one instance of the object. You would need to use new-object to create more than one instance. – jdweng Dec 23 '22 at 10:05
  • The question could use more detail. – js2010 Dec 25 '22 at 14:39

1 Answers1

1

Not at all sure what your variable $ReportDetails is like, but I think you mean to get an array of objects with chosen properties about each disk.

Something like this:

$array = foreach ($diskName in $r.storageProfile.DataDisks.Name) {
    $azDisk   = Get-AzDisk -ResourceGroupName $ResourceGroupName -DiskName $diskName
    $dataDisk = $r.storageProfile.DataDisks | Where-Object {$_.Name -eq $diskName}
    [PsCustomObject]@{
        VMName            = $r.Name
        DiskName          = $azDisk.Name
        DiskSizeGB        = $azDisk.DiskSizeGB
        sku               = $azDisk.Sku.Name
        Lun               = $dataDisk.lun
        Caching           = $dataDisk.Caching
        DiskIOPSReadWrite = $azDisk.DiskIOPSReadWrite
        DiskMBpsReadWrite = $azDisk.DiskMBpsReadWrite
    }
}
$array | Out-GridView
Theo
  • 57,719
  • 8
  • 24
  • 41