Using PowerShell String Concatenation

If you work with PowerShell for more than a hot minute, it’s likely that you’ll need to concatenate strings or variables at some point. Whether it’s combining multiple strings into one or merging values in a CSV file, string concatenation is a powerful skill to have in your scripting toolkit.

For this tutorial, I’m going to step you through a few different methods of string concatenation. I’ll provide examples from basic to more advanced techniques in hopes that you’ll be able to adapt and leverage one or more of them to your current problem.

Mastering the + Operator

The + (plus) operator is the simplest method for concatenating strings in PowerShell. It’s used to combine two or more variables or strings into a single string. Here’s how it works:

Input:

$string1 = "Hello"
$string2 = " Friend"
$concatenatedString = $string1 + $string2

Output:

Hello Friend

In this example, the + operator is used to concatenate the values of $string1 and $string2 into a single string. The output of this expression is “Hello Friend”.

Note the space before Friend in $string2.

To add more strings just add more + operators:

Input:

$string1 = "Hello"
$string2 = " Friend"
$string3 = "!"
$concatenatedString = $string1 + $string2 + $string3

Output:

Hello Friend

So, about that pesky space… Here is another way to approach it:

Input:

$greeting = "Hello"
$name = "Friend"
$concatenatedString = $greeting + " " + $name

Output:

Hello Friend

This example combined the values of $greeting and $name, separated by a space.

Before we get too far, it’s important to consider the data type of the variables. If a variable contains a number, you may need to convert it to a string before concatenating it with other strings.

You can use the ToString() method to convert a variable to a string, like this:

Input:

$number = 52
$string = $number.ToString()
$concatenatedString = "The number is " + $string

Output:

The number is 52

Here ToString() converts the value of $number to a string, which is then concatenated with another string using the + operator.

The + operator is a simple method but, for large strings, it can have performance issues. It’s recommended to use other methods such as the Join-String cmdlet or the System.Text.StringBuilder class when things need be more performant. I’ll get into those in a minute.

Formatting Strings with the -f Operator

The -f operator is typically used for string formatting, but it can also be used for string concatenation. You can use it to insert values into a string template and create a new string with those values. Here’s an example:

Input:

$greeting = "Hello"
$name = "Friend"
$formattedString = "{0} {1}" -f $greeting, $name

Output:

Hello Friend

Here the -f operator is used to insert the values of $greeting and $name into a string template resulting in the output “Hello Friend”.

Joining Strings with the -join Operator

The -join operator in PowerShell is used for joining an array of strings into a single string. It takes an array of strings as input and returns a single string that’s the concatenation of the input strings separated by a specified delimiter. Here it is in action:

Input:

$strings = "Hello", "Friend"
$joinedString = $strings -join " "

Output:

Hello Friend

The -join operator was used to join the elements of the array $strings into a single string, separated by a space.

Concatenating Strings with the Join-String Cmdlet

As mentioned earlier, the Join-String cmdlet is a more efficient way of concatenating strings. Just as before, it takes an array of strings as input and returns a single concatenated string. For example:

Input:

$strings = "Hello", " Friend"
$concatenatedString = Join-String $strings

Output:

Hello Friend

If you want to specify a delimiter between the concatenated strings, you can use the -Delimiter parameter:

Input:

$strings = "Hello", "Friend"
$concatenatedString = Join-String $strings -Delimiter " "

Output:

Hello Friend

In this example, the Join-String cmdlet is used to concatenate the elements of the array $strings into a single string, separated by a space.

Merging Strings with the Concat() Method of System.String

The Concat() method of the System.String class can be used for more efficient concatenation of strings. It takes an array of strings as input and returns a single string that is the concatenation of the input strings. For example:

Input:

$string1 = "Hello"
$string2 = " Friend"
$concatenatedString = [System.String]::Concat($string1, $string2)

Output:

Hello Friend

Building Strings with System.Text.StringBuilder

Continuing the theme of efficiency, you can use the System.Text.StringBuilder class, provides a mutable (modifiable) string object, to concatenate strings as well. Example:

Input:

$sb = New-Object System.Text.StringBuilder
$sb.Append("Hello")
$sb.Append(" Friend")
$concatenatedString = $sb.ToString()

Output:

Hello Friend

Here we see a new instance of the System.Text.StringBuilder class created and two strings are appended to it using the Append method. The ToString method is then used to convert the System.Text.StringBuilder object to a string, which is the concatenation of the strings that were appended to it.

System.Text.StringBuilder is designed to be more efficient for large strings, as it provides an internal buffer that can be resized dynamically, reducing the number of memory allocations required. Thus, it is more scalable. When concatenating strings using the + operator or the Concat() method, a new string object is created each time a string is concatenated, and this can be slow for large strings.

Merging Columns in a CSV File: A Real-Friend Scenario

Merging and otherwise manipulating columns in a CSV file for output is a common task to streamline with PowerShell. You might have a CSV file with two columns, and you want to merge the values of those columns into a new third single column. We can read in a CSV file and then process it with any of the concatenation methods I’ve shown you so far.

Let’s use the most basic + operator to show a real-world example:

$csv = import-csv "C:\temp\input.csv"
$csv | select FirstName,LastName, @{n=’FullName’;e={$_.FirstName + ” ” + $_.LastName}}
$csv | export-csv "C:\temp\output.csv" -NoTypeInformation

Here, the import-csv cmdlet is used to import the contents of a CSV file into an object. A script is used to create a new column that is then filled with the concatenation of the values of the FirstName and LastName properties. Then, the export-csv cmdlet is used to export the modified objects to a new CSV file.

Best Practices for String Concatenation in PowerShell

When you’re deciding on a method, there are several best practices to keep in mind.

  1. Size: If the strings are large, consider using the System.Text.StringBuilder class, as this method is more efficient and thus mor performant.
  2. Variables: If a variable contains a number, consider converting it to a string using the ToString() method before concatenating it with other strings.
  3. Repetition: If you need to concatenate the same strings multiple times, consider storing the concatenated string in a variable and reusing it.

Recommended Tool: ManageEngine OpManager

  • Multi-vendor Network Monitoring
  • Simple Installation & Setup
  • Intuitive UI
  • Complete Visibility
  • Intelligent Detections
  • Easy Resolutions

Leave a Reply

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