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?

2 thoughts on “Joining strings in pipeline”
  1. Try this built-in functionality:
    PS C:\> [string]::Join(‘,’,(“one”,”two”,”three”))
    one,two,three
    PS C:\>
    PS C:\> [string]::Join(‘,’,1..20)
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20

  2. Thank you. I need this for Select-Object pipeline.
    This is my version:
    unction Join-String2
    {
    [CmdletBinding()]
    param
    (
    [Parameter(Mandatory = $true, ValueFromPipeline = $true)][string]$String,
    [Parameter(Position = 1)][string]$Delimiter = “”
    )
    BEGIN
    {
    [bool]$isEmpty = $true
    [System.Int32]$StartingSize = 255
    [System.Text.StringBuilder]$sb = New-Object System.Text.StringBuilder -ArgumentList $StartingSize
    }
    PROCESS
    {
    if($isEmpty)
    {
    $sb.Append($String) | Out-Null
    $isEmpty = $false
    }
    else { $sb.Append($Delimiter).Append($String) | Out-Null
    }
    }
    END { return ($sb.ToString()) }
    }
    Get-Process | Select-Object -ExpandProperty ProcessName | Join-String2 ‘;’

Leave a Reply

Your email address will not be published. Required fields are marked *