How to Concatenate Strings in PowerShell (2 Methods)


There are two common ways to concatenate strings in PowerShell:

Method 1: Use plus ( + ) sign

Write-Host $first_string + " " + $second_string

Method 2: Use join operator

$first_string,$second_string -join " "

Both of these examples concatenate the first_string and second_string variables together using a space as a separator.

The following examples show how to use each method in practice.

Example 1: Concatenate Strings in PowerShell Using Plus Sign

One of the most common ways to concatenate strings together in PowerShell is to simply use a plus (+) sign in between the string variables with a specific separator.

For example, we can use the following syntax to concatenate two strings together using a single space as a separator:

$first_string = "I really hope"
$second_string = "that you are having a great day"

$final_string = $first_string + " " + $second_string

Write-Host $final_string

The following screenshot shows how to use this syntax in practice:

PowerShell concatenate strings

Notice that the two strings have been concatenated together with a single space in between them.

Example 2: Concatenate Strings in PowerShell Using Join Operator

Another common way to concatenate strings together in PowerShell is to use the join operator followed by a specific separator.

For example, we can use the following syntax to concatenate two strings together using a single space as a separator:

$first_string = "I really hope"
$second_string = "that you are having a great day"

$first_string,$second_string -join " "

The following screenshot shows how to use this syntax in practice:

PowerShell concatenate strings using join operator

We can see that the two strings have been concatenated together with a single space in between them.

If you would like to concatenate strings using a different separator, you can specify it after the join operator.

For example, we can use the following syntax to concatenate the string variables together using a dash as a separator:

$first_string = "I really hope"
$second_string = "that you are having a great day"

$first_string,$second_string -join "-"

The following screenshot shows how to use this syntax in practice:

Notice that the two strings have been concatenated together with a dash in between them.

Note: The join operator is particularly useful when concatenating several string variables together so that you don’t have to manually type out a plus sign after each variable name.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply