Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active August 27, 2023 08:46
Show Gist options
  • Save santisq/8dc98c4c7b61281ffad0defeaa6f43ec to your computer and use it in GitHub Desktop.
Save santisq/8dc98c4c7b61281ffad0defeaa6f43ec to your computer and use it in GitHub Desktop.
$Array1 = 1, 2, 3
$Array2 = 'Joe Bloggs', 'John Doe', 'Jane Doe'
$Array3 = 'Yes', 'No'
$Array4 = 'hello', 'world', 123, 456
# Positional Binding
Join-Array $Array1, $Array2, $Array3, $Array4 -Columns Number, Name, Valid, Test
# Pipeline Input
$Array1, $Array2, $Array3, $Array4 | Join-Array -Columns Number, Name, Valid, Test
# Expected Output for both statements:
#
# Number Name Valid Test
# ------ ---- ----- ----
# 1 Joe Bloggs Yes hello
# 2 John Doe No world
# 3 Jane Doe 123
# 456
function Join-Array {
[CmdletBinding()]
param(
[parameter(ValueFromPipeline, Mandatory)]
[object[]] $InputObject,
[parameter(Mandatory)]
[string[]] $Columns
)
begin {
$inputDict = [ordered]@{}
$index = 0
}
process {
try {
if($MyInvocation.ExpectingInput) {
return $inputDict.Add($Columns[$index++], $InputObject)
}
foreach($item in $InputObject) {
$inputDict.Add($Columns[$index++], $item)
}
}
catch {
if($_.Exception.InnerException -is [ArgumentNullException]) {
$errorRecord = [Management.Automation.ErrorRecord]::new(
[Exception] 'Different count between input arrays and Columns.',
'InputArrayLengthMismatch',
[Management.Automation.ErrorCategory]::InvalidOperation,
$InputObject
)
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
$PSCmdlet.ThrowTerminatingError($_)
}
}
end {
foreach($pair in $inputDict.GetEnumerator()) {
$count = $pair.Value.Count
if($count -gt $max) {
$max = $count
}
}
for($i = 0; $i -lt $max; $i++) {
$out = [ordered]@{}
foreach($column in $inputDict.PSBase.Keys) {
$out[$column] = $inputDict[$column][$i]
}
[pscustomobject] $out
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment