PowerShell is very advanced scripting and programming language that provides different methods in order to concatenate strings. The string type is used to store single or more characters. String Concatenation
is the operation to join multiple strings together. In this tutorial, we examine different operators, options, and commands to concatenate strings in PowerShell.
Concatenate Strings Using + Operator
The +
or plus operator is a very well-known operator to sum or concatenate strings in PowerShell. Simply putting the + operator between string literals or string variables concatenates these strings. In the following example, we concatenate string literals.
$str = "I"+" love "+" Windowstect."
Alternatively, we can concatenate string variables with the + operator.
$str1="I"
$str2=" love "
$str3=" Windowstect."
$str=$str1+$str2+$str3
Also, both string literals and string variables can be used to concatenate with the + operator.
$str1="I"
$str2=" love "
$str=$str1+$str2+" Windowstect."
Concatenate Strings Using -f Option
PowerShell string type provides the -f
option for formattings reasons. But the -f options can be used to concatenate strings into a single string. The strings which are concatenated are provided as parameters to the -f
option. Also, the provided strings are expressed with {0} {1} {2} {3}
in the string.
$str = "{0}{1}{2}" -f "I"," love "," Windowstect."
Concatenate Strings Using Write-Host Command
The Write-Host
command is used to put specified values into the command line interface. But the Write-Host command can be also used to concatenate strings.
$str1="I"
$str2=" love "
$str3=" Windowstect."
Write-Host "$($str1)$($str2)$($str3)"
Concatenate Strings Using -join Operator
The -join
operator is used to joining new values or strings into an existing string. The new values are provided as parameters to the -join operator.
$str1="I"
$str2=" love "
$str3=" Windowstect."
$str = $str1,$str2,$str3 -join ""
Concatenate Strings Using Concat() Command
PowerShell is a complete programming language that runs over .NET runtime. The Concat()
method is provided via the System.String
namespace of the .Net library. The Concat() can be used to concatenate strings provided as parameters to this method.
$str1="I"
$str2=" love "
$str3=" Windowstect."
$str = [System.String]::Concat($str1,$str2,$str3)