0

Hi there are two tables below

Computer A
------------
20.03
20.02
20.01       
Computer B
------------
20.03
20.02
20.01
XXX
XXX

Hi I have a question is I want to merge into a CSV,so I need to achieve first below as :

Computer A      Computer B
------------    ------------
20.03           20.03
20.02           20.02
20.01           20.01  
                XXX
                XXX

How can I do? I have many something like those tables that need to merge I tried some many time, just can't be able to do that

Dukeyu
  • 67
  • 1
  • 7
  • are the tables literal text tables or are they some sort of object? if they are just text, are they individual multiline strings OR are they an array of single line strings? – Lee_Dailey May 28 '20 at 14:38
  • @Lee_Dailey They are the PSCustomObject I think. $str is ComputerA $str |Select-Object @{Label='ComputerA';Expression={$_.ComputerA}},@{Label='ComputerB';Expression={ ?? }} ?? is I don't know how to do – Dukeyu May 28 '20 at 14:43
  • @Dukeyu - please, add the _very important_ info to your Question. those are not tables ... they are PSCOs and the display is entirely wrong for dealing with the actual object. – Lee_Dailey May 28 '20 at 17:17

1 Answers1

0

Start by turning both arrays into hashtables - this way we can quickly lookup whether a value exists in one or both:

$ComputerATable = @{}
$AObjects |ForEach-Object { $ComputerATable[$_.'Computer A'] = $_ }

$ComputerBTable = @{}
$AObjects |ForEach-Object { $ComputerATable[$_.'Computer B'] = $_ }

Now we just need to loop through all distinct computer names to build our "merged table":

$merged = $ComputerATable.Keys,$ComputerBTable.Keys |Sort-Object |ForEach-Object {
  # Create a new object with the value (if present) from either table
  [pscustomobject]@{
    'Computer A' = if($ComputerATable.ContainsKey($_)){ $_ }
    'Computer B' = if($ComputerBTable.ContainsKey($_)){ $_ }
  }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206