- Generate arrays via foreach instead of
+=which recreates the entire array each time - Declare arrays using simplified syntax: just a list of comma-separated elements
# help Format-Table recognize all added properties
Add-Member ([ordered]@{
DEV = $result[0].DEV
TEST = $result[0].TEST
PROD = $result[0].PROD
}) -Force -InputObject $result[0]
$result | ft -auto
TheWhile the above code is approximately 2 times faster than the original one, it's possible to make it 5 times faster in PowerShell 5 and newer by adding properties directly via .NET method so the second block may be generalized to process any number of input arrayswould become as follows:
$addedId = @{}
$result = Sort Id -input @(
foreach ($sourceName in 'DEV', 'TEST', 'PROD') {
$source = Get-Variable $sourceName -value
$prop = [PSNoteProperty]::new($sourceName, 'Y')
foreach ($item in $source) {
Add-Member $sourceName 'Y' -InputObject $item.PSObject.Properties.Add($prop)
if (!$addedId[$item.Id]) {
$addedId[$item.Id] = $true
$item
}
}
}
)