Joining strings in pipeline
In PowerShell, I’ve been joining string arrays for quite some time with the join operator which concatenates a set of strings into a single string. Today however, I found myself in need to join strings that are coming from the pipeline, without previously saving the result into a variable. Guess what, there is nothing ready, out of the box, that will do the trick.
In case you would like to join the strings with new line character as a delimiter (or with no delimiter at all), you can always use Out-String
cmdlet, eventually with it’s -NoNewline
parameter. However, as far as I know, there are no cmdlets available that will perform this simple operation.
This pushed me to write a simple one that should do the trick.
function Join-String { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)][string]$String, [Parameter(Position = 1)][string]$Delimiter = "" ) BEGIN {$items = @() } PROCESS { $items += $String } END { return ($items -join $Delimiter) } }
Invoking this cmdlet is quite trivial, however, for completeness here is an example.
$commaSepareted = @("one","two","three") | Join-String ","
That’s it folks!
Is there a more elegant or out of the box way to achieve the same?