Last active
August 27, 2023 08:46
-
-
Save santisq/8dc98c4c7b61281ffad0defeaa6f43ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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