Home > Mobile >  Array getting overwritten in powershell
Array getting overwritten in powershell

Time:12-27

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.

CodePudding user response:

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
  • Related