Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

5.10 Combine Strings into a Larger String

Problem

You want to combine several separate strings into a single string.

Solution

Use PowerShell’s unary -join operator to combine separate strings into a larger string using the default empty separator:

PS > -join ("A","B","C")
ABC

If you want to define the operator that PowerShell uses to combine the strings, use PowerShell’s binary -join operator:

PS > ("A","B","C") -join "`r`n"
A
B
C

To use a cmdlet for features not supported by the -join operator, use the Join-String cmdlet:

PS > 1..5 | Join-String -DoubleQuote -Separator ','
"1","2","3","4","5"

Discussion

The -join operator provides a natural way to combine strings. When used with no arguments (the unary join operator), it joins the list using the default empty separator. When used between a list and a separator (the binary join operator), it joins the strings using the provided separator.

Aside from its performance benefit, the -join operator solves an extremely common difficulty that arises from trying to combine strings by hand.

When first writing the code to join a list with a separator (for example, a comma and a space), you usually end up leaving a lonely separator at the beginning or end of the output:

PS > $list = "Hello","World"
PS > $output = ""
PS >
PS > foreach($item in $list)
{
    $output += $item + ", "
}

PS > $output
Hello, World,

You can resolve this by adding some extra logic to the foreach loop:

PS > $list = "Hello","World"
PS > $output = ""
PS >
PS > foreach($item in $list)
{
    if($output -ne "") { $output += ", " }
    $output += $item
}

PS > $output
Hello, World

Or, save yourself the trouble and use the -join operator directly:

PS > $list = "Hello","World"
PS > $list -join ", "
Hello, World

If you have advanced needs not covered by the -join operator, the .NET methods such as [String]::Join() are of course available in PowerShell.

For a more structured way to join strings into larger strings or reports, see Recipe 5.6.

See Also

Recipe 5.6, “Place Formatted Information in a String”