When working with PowerShell, you may often need to combine or concatenate strings. Concatenation is the process of combining multiple strings to create a single string. PowerShell provides several options for concatenating strings, each with advantages and use cases.
In this blog post, we will explore different PowerShell concatenate string techniques.
Table of Contents
String Expansion
String expansion is a straightforward and intuitive way to concatenate strings in PowerShell. It allows you to include variables and expressions within double-quoted strings. When PowerShell encounters a variable or expression enclosed in $(), it evaluates it and replaces it with its value in the resulting string.
Here’s an example of string expansion in PowerShell:
$firstName = "John"
$lastName = "Doe"
$fullName = "$firstName $lastName"
$fullName
In this example, the variable $fullName will be assigned the concatenated value of $firstName and $lastName, resulting in “John Doe”.
String expansion is a convenient option when you need to concatenate a few strings or include variables within a larger string.
Some more examples:
# Username
"$firstName.$lastName"
# Usre principal name or email address
"$firstName.$lastName@domain.com"
String.Concat() Method
The String.Concat() method in PowerShell allows you to concatenate multiple strings by passing them as separate arguments to the method. This PowerShell concatenate string method combines all the input strings and returns a new string, that is, the concatenation of the inputs.
Here’s an example of using the String.Concat() method:
$greeting = "Hello"
$name = "John"
$message = [String]::Concat($greeting, " ", $name)
In this example, the Concat() method combines the $greeting, a space character, and the $name variables, resulting in “Hello John”.
The String.Concat() method is useful when you have a known number of strings to concatenate and want to specify each string as an argument explicitly.
String Concatenation Operator (+)
PowerShell supports the + operator for string concatenation. This operator allows you to combine two or more strings into a single string. Note that this PowerShell concatenate string operator is a shorthand of the String.Concat() method.
Here’s an example of using the string concatenation operator:
$firstName = "John"
$lastName = "Doe"
$fullName = $firstName + " " + $lastName
$fullName
In this example, the + operator concatenates the $firstName, a space character, and the $lastName variables, resulting in “John Doe”.
The string concatenation operator is a concise and commonly used approach for concatenating strings in PowerShell.
Be careful when using the + PowerShell concatenate string operator when concatenating strings and numbers because it is also a math operator (addition). You cannot perform addition using strings and numbers. For example, run the below command in PowerShell.
$age = 30
$age + " years old"
This command returns an error because $age is a number value, and PowerShell interprets the + operator as an addition operation instead of string concatenation.
The same happens even if you don’t use variables and directly specify the number like so:
30 + " years old."
So how can we avoid this error? You can explicitly specify the variable’s data type as a string like so:
[string]$age = 30
Or enclose the number in quotes.
"30"
Either way, the resulting object is of a string data type which you can verify by calling the GetType() method.
$age.GetType()
"30".GetType()
So when we apply this technique, we’ll get the expected results without errors.
[string]$age = 30
$age + " years old."
"30" + " years old."
In summary, when you start a PowerShell concatenate string operation with a number (i.e., number + string + string), the + operator is interpreted as a mathematical addition operator.
But suppose you start the concatenation with a string value (i.e., string + number + string). In that case, every element is automatically considered a string, and the + operator is interpreted as a string concatenation operator.
Related post. PowerShell: Convert String to Integer
String.Format() Method
The String.Format() PowerShell concatenate string method provides a flexible way to concatenate strings in PowerShell by allowing you to specify placeholders within a format string and supply corresponding values.
Here’s an example of using the String.Format() method:
$firstName = "John"
$lastName = "Doe"
$fullName = [String]::Format("Full name: {0} {1}", $firstName, $lastName)
$fullname
In this example, the format string “Full name: {0} {1}” contains placeholders {0} and {1} that are replaced with the values of $firstName and $lastName, respectively.
The String.Format() method is beneficial when creating a formatted string with placeholders for dynamic values.
For example, let’s create a hash table of fruits with their corresponding colors.
$fruits = [ordered]@{
Banana = 'yellow'
Avocado = 'green'
Apple = 'red'
Orange = 'orange'
}
Using the String.Format() method and for loop, we can display these values in this format “[fruit name] is [color name]”
for ($i = 0 ; $i -lt $fruits.Count; $i++ ) {
[String]::Format("{0} is {1}", $fruits.Keys[$i], $fruits.Values[$i])
}
String Format Operator (-f)
PowerShell provides the -f operator, also known as the format operator, which allows you to perform string formatting and concatenation concisely and readably.
Note. The -f operator is a shorthand of the String.Format() method.
Here’s an example of using the format operator:
$firstName = "John"
$lastName = "Doe"
$fullName = "Full name: {0} {1}" -f $firstName, $lastName
In this example, the format operator -f is applied to the string “Full name: {0} {1}”, and the values of $firstName and $lastName are used to replace the placeholders {0} and {1}.
The format operator is an elegant way to concatenate strings and perform formatting in PowerShell. Since it is a shorthand of the String.Format() method, it is also excellent for displaying dynamic values.
$fruits = [ordered]@{
Banana = 'yellow'
Avocado = 'green'
Apple = 'red'
Orange = 'orange'
}
for ($i = 0 ; $i -lt $fruits.Count; $i++ ) {
"{0} is {1}" -f $fruits.Keys[$i], $fruits.Values[$i]
}
String.Join() Method
The String.Join() PowerShell concatenate string method allows you to concatenate an array of strings using a specified separator. It takes two arguments: the separator string and an array of strings to concatenate.
Here’s an example of using the String.Join() method:
$colors = "Red", "Green", "Blue"
$colorList = [String]::Join(", ", $colors)
In this example, the Join() method concatenates the strings in the $colors array, separating them with a comma and a space, resulting in “Red, Green, Blue”.
The String.Join() method is handy when you have an array of strings that you want to concatenate with a specific separator.
For another example, let’s get the first five services on the computer and join their DisplayName property values with the “ | ” (space pipe space) characters.
$services = Get-Service | Select-Object -First 5
[String]::Join(" | ", $services)
You can achieve the same with a one-liner. This time, let’s join them with a new line character (`n)
[String]::Join("`n", $(Get-Service | Select-Object -First 3).DisplayName)
String Join Operator (-join)
PowerShell also provides the -join operator, which allows you to concatenate an array of strings without specifying a separator explicitly. The -join operator joins the elements of an array into a single string without any delimiter.
Here’s an example of using the join operator:
$colors = "Red", "Green", "Blue"
-join $colors
In this example, the -join operator concatenates the strings in the $colors array without any separator, resulting in “RedGreenBlue”.
The join operator is useful when you want to concatenate strings in an array without any separator between them. Like, when creating filenames with a date.
$name = "backup_"
$now = Get-Date -Format "yyyy_MM_dd"
$ext = ".txt"
-join @($name, $now, $ext)
But this operator is a shorthand of the String.Join() method, which means you can also specify a delimiter. To do so, you must move the -join operator after the array and followed by the delimiter.
$colors = "Red", "Green", "Blue"
$colors -join ' > '
Conclusion
Concatenating strings in PowerShell is a common task, and knowing the various methods available can help you choose the most suitable approach for your specific requirements.
In this blog post, we explored different options for concatenating strings in PowerShell, including string expansion, the String.Concat() method, the string concatenation operator, the String.Format() method, the format operator, the String.Join() method and the join operator.
Each method has its strengths and use cases, so it’s essential to understand their differences and choose the most appropriate one for your PowerShell scripting needs.