2

Below is the code I am writing and facing some difficulty getting the objects joined . Please help me on that. Though I used array += , only one object is getting resulted out . Please help me get corrected.

$array = @()
$DC1Ser = Get-Content -Path C:\temp\DC1ServersListMain.txt
$DC1 = foreach($ls in $DC1Ser){
Get-WmiObject -ComputerName $ls -Class Win32_logicaldisk -Filter "DriveType = '3'" | `
?{$_.DeviceID -like "U:"} |`
Select @{l='HostName';e={$ls}}, @{l="DC1UFreeGB";e={"{0:N2}" -f ($_.FreeSpace/1GB)}}
}

$DC2Ser = Get-Content -Path c:\temp\DC2ServerListMain.txt
$DC2 = foreach($ts in $DC2Ser){
Get-ChildItem -Path "\\$ts\U$\DL" | Measure-Object -Property Length -Sum |`
select  @{l='HostName';e={$ts}},@{label = "DLSizeGB";e= {"{0:N2}" -f ($_.sum/1GB)}} 
}

 foreach($i in $DC2){
 $array  += [PSCustomObject]@{ 
 DC2Host  = $i.HostName   
 DLSizeGB = $i.DLSizeGB
 }
 }
 foreach($e in $DC1){

 $array  += [PSCustomObject]@{ 
    DC1Host     = $e.HostName
    DC1UFreeGB  = $e.DC1UFreeGB
 }

 }
 $array
Learning_Learning
  • 317
  • 1
  • 5
  • 18
  • 1
    When objects have different properties, there may be display issues. The first object in the pipeline determines what properties are seen for the remaining objects. You will need the first object to contain all of your possible properties. – AdminOfThings Aug 10 '21 at 14:08
  • When `Format-Table` formatting is applied, which happens implicitly if an object has 4 or fewer properties, the _first_ object in a collection locks in all display properties. If subsequent objects have _different properties_, only those they share with the first one are displayed; if a given object shares none, a blank line is displayed. This is only a _display problem_, as you can verify by piping the objects to `... | Format-List`. See [the linked duplicate](https://stackoverflow.com/a/45705068/45375) for more information. – mklement0 Aug 10 '21 at 14:48
  • 1
    As an aside: Incrementally "extending" an array in a loop with `+=` is inefficient, because a _new_ array must be created behind the scenes _in every iteration_, given that arrays are fixed-size collections; a much more efficient approach is to use the `foreach` loop as an _expression_ and let PowerShell automatically collect the outputs in an array: `[array] $outputs = foreach (...) { ... }` - see [this answer](https://stackoverflow.com/a/60708579/45375). – mklement0 Aug 10 '21 at 14:55

0 Answers0