Search code examples
powershellpowershell-5.0

Push output of results to an array


I'm running the below scrpt to return a resultset of disk capacity from a list of all available servers within our estate. I'd like to append the outputs and combine them into one dataset to make it easy to display and interrogate. I am aware of how to append values to an array with one column however as this would require multiple, I'm not sure how to acheive this. Is it possible to append the result set from this output to an array?

$myarray = @("")
$servers =
   @(
         'SERVER1'
        ,'SERVER2'
        ,'SERVER3'
        ,'SERVER4'
        ,'SERVER5'
        ,'SERVER6'

    )
$wmiQuery = @"
SELECT
    SystemName,Name,DriveType,FileSystem,FreeSpace,Capacity,Label
FROM
    Win32_Volume
"@

Foreach ($server in $servers)
{

        Get-WmiObject -ComputerName $server -Query $wmiQuery| Select-Object @{Name = "Computer"; Expression={$server}},Name,
        Label,
        @{Name = "SizeInGB"; Expression={"{0:N2}"-f ($_.Capacity/1GB)}},
        @{Name = "UsedSizeInGB"; Expression={"{0:N2}"-f (($_.Capacity - $_.FreeSpace)/1GB)}},
        @{Name = "FreeSizeInGB"; Expression={"{0:N2}"-f ($_.FreeSpace/1GB)}},
        @{Name = "FreePerc"; Expression={"{0:N2}"-f (($_.FreeSpace/1GB)/($_.Capacity/1GB))}}|Where-Object FreePerc -LE 0.16|Format-Table

}

Solution

  • You can do this by storing the output of your foreach loop to an array.

    $servers = @('SERVER1','SERVER2','SERVER3','SERVER4','SERVER5','SERVER6')
    $wmiQuery = @"
    SELECT
        SystemName,Name,DriveType,FileSystem,FreeSpace,Capacity,Label
    FROM
        Win32_Volume
    "@
    $myarray = Foreach ($server in $servers)
    {
    
        Get-WmiObject -ComputerName $server -Query $wmiQuery |
          Select-Object @{Name = "Computer"; Expression={$server}},Name,Label,
          @{Name = "SizeInGB"; Expression={"{0:N2}"-f ($_.Capacity/1GB)}},
          @{Name = "UsedSizeInGB"; Expression={"{0:N2}"-f (($_.Capacity - $_.FreeSpace)/1GB)}},
          @{Name = "FreeSizeInGB"; Expression={"{0:N2}"-f ($_.FreeSpace/1GB)}},
          @{Name = "FreePerc"; Expression={"{0:N2}"-f (($_.FreeSpace/1GB)/($_.Capacity/1GB))}}|Where-Object FreePerc -LE 0.16
    
    }
    $myarray | Format-Table
    

    I removed the Format-Table from the loop because you should only use the Format-* commands when you are showing your final output not when you are going to be using that output for other processing. The $myarray variable will be an array with each element being an object with the properties from your Get-WmiObject query.