Skip to content

Instantly share code, notes, and snippets.

@PrzemyslawKlys
Last active November 5, 2018 08:24
Show Gist options
  • Save PrzemyslawKlys/46bbb9e1acb24fe09b530d071f92cbe6 to your computer and use it in GitHub Desktop.
Save PrzemyslawKlys/46bbb9e1acb24fe09b530d071f92cbe6 to your computer and use it in GitHub Desktop.
Merge-Array - Adding field
$Array1 = @()
$Element1 = [PSCustomObject] @{ Name = 'Company1'; Count = 259 }
$Element2 = [PSCustomObject] @{ Name = 'Company2'; Count = 300 }
$Array2 = @()
$Element3 = [PSCustomObject] @{ Name = 'Company1'; Count = 25 }
$Element4 = [PSCustomObject] @{ Name = 'Company2'; Count = 100 }
$Array1 += $Element1
$Array1 += $Element2
$Array2 += $Element3
$Array2 += $Element4
$Array1 | Format-Table -AutoSize
$Array2 | Format-Table -AutoSize
function Merge-Array {
param(
$Array1,
$Array2
)
$NewArray = @()
foreach ($A in $Array1) {
#$A.PSObject.Properties.Name
$NewArray += [pscustomobject] @{ Name = $A.Name; Count = $A.Count; Count1 = '' }
}
foreach ($B in $NewArray) {
foreach ($A in $Array2) {
if ($A.Name -eq $B.Name) {
$B.Count1 = $A.Count
}
}
}
return $NewArray
}
Merge-Array $Array1 $Array2 | Format-Table -AutoSize
@PrzemyslawKlys
Copy link
Author

First Array:

Name     Count
----     -----
Company1   259
Company2   300

2nd Array

Name     Count
----     -----
Company1    25
Company2   100

Final (merged) Array:

Name     Count Count1
----     ----- ------
Company1   259     25
Company2   300    100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment