Updated September 16, 2023
Introduction to PowerShell Concatenate String
The PowerShell String Concatenation is the process of combining one or more strings. String concatenation is primarily achieved using the “+” operator. There are other ways, like enclosing the strings inside double quotes, using a join operator, or using the -f operator.
Table of Contents
Syntax:
The ‘+’ operator is used to concatenate strings. Let’s see a sample example below:
Code:
Write-Host "String Concat in Powershell"
Write-Host "Basic Example"
$str1="My name is John."
$str2="Am from Africa"
Write-Host "Concatenated text is below"
$str1+$str2
Output:
Key Highlights
- PowerShell is customizable and independent software where vendors and enterprise developers can customize their tools and utilities.
- Concatenation is a method of joining two strings using certain operators.
- The PowerShell concatenation of strings happens with string builder, string with numbers, built-in functions, and operators.
Features of PowerShell
The key features and descriptions for the PowerShell:
- Get-Command creates a list of all the commands from cmdlets and functions of the device. Cmdlets manage the registry, processes, services, event logs, and other system administration functions. It uses Windows Management Instrumentation (WMI) to perform all these functions.
- The get-Help cmdlet helps the users learn more about the principles of PowerShell and its particular components.
- Using Windows Management Instrumentation and WS-Management, the admins can operate the devices remotely.
- With the PowerShell pipe operator (|), you can link the commands together. In this approach, the output of one command is the input for the upcoming command in the pipeline manner. The PowerShell pipeline operator allows the flow of objects rather than text strings from one cmdlet to another.
- PowerShell scripting language provides support for the already existing scripts and command-line tools.
- The cmdlets and system data stores have a common naming convention, and they use common syntax making data sharing easy.
- Command-based navigation in a simplified manner allows the users to navigate the registry and other data stores.
- PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly.
Examples of PowerShell Concatenate String
It is not necessary that only the ‘+’ sign must be used to concatenate strings. This example will show the various ways in which strings can be concatenated.
Example #1 – With separators
Code:
Write-Host "String concatenation without + operator"
$str1="first sentence"
$str2="second sentence"
Write-Host "After concatenation"
"$str1$str2"
Write-Host "Example of concatenation with separators"
$str1+ "," +$str2
$str3="Powershell is the most underrated language"
$str4=" it can do many wonders"
Write-Host "Another way"
"$str3!!!!,$str4"
Output:
Example #2 – String and Integer Concatenation
Code:
Write-Host "String concatenation demo of int and string"
$string1=75
$string2="my name is Alex"
$string3=$string1 + $string2
Output:
In the above code, if the variables are swapped before concatenation, then the error will not occur.
Input:
Write-Host "String concatenation demo of int and string"
$string1=75
$string2="my name is Alex"
$string3=$string2 + $string1
Write-Host $string3
Output:
Alternatively, the above can be achieved by using string substitution.
Code:
Write-Host "String concatenation demo of int and string"
$int1=75
$string2="my name is Alex"
Write-Host "string concatenation using string Substitution"
"$($int1) , $($string2)"
Output:
Example #3 – Using -f Operator
Code:
Write-Host "String concatenation using f operator"
$str1="This is the first sentence"
$str2="This is the second sentence"
$str3="This is the third Sentence"
Write-Host "Concatenated string is below"
"{0}.{1}.{2}." -f $str1,$str2,$str3
Output:
Example #4 – Using Join Operator
Code:
Write-Host "String concatenation using Join operator"
$str1="This is the first sentence"
$str2="This is the second sentence"
$str3="This is the third Sentence"
Write-Host "Concatenated string is below"
$str1,$str2,$str3 -join "!!!"
Output:
Example #5 – Remove Default Space in Write-Host
Code:
$str1="This is the first sentence"
$str2="This is the second sentence"
$str3="This is the third Sentence"
Write-Host "Concatenated string is below" $str1 $str2 $str3 -Separator ''
Output:
Example #6 – Using Concat() and String Builder
Code:
Write-Host "String concatenation using concat method"
$str1="This is the first sentence"
$str2="This is the second sentence"
$str3="This is the third Sentence"
Write-Host "Concatenated string is below"
[System.String]::Concat($str1,".",$str2,".",$str3)
Write-Host "String concatenation using string builder"
$SB = New-Object -TypeName System.Text.StringBuilder
$null = $SB.Append("First Sentence")
$null = $SB.Append("Second Sentence")
$null = $SB.Append("Third Sentence")
$null = $SB.Append("Fourth Sentence")
$SB.ToString()
Output:
Example #7
Code:
$string1 = @"
My name is Ella
Am from USA
Am a freelancer
"@
$string2 = @"
First sentence of the example
Second sentence of the example
Third Sentence of the example
"@
$string1 , $string2 -join "`n"
Output:
Example #8
Concatenate two column values in a CSV and export them to a new column.
In the below example, the CSV has two columns – FirstName and LastName. The below script will merge the two column values and export them to a new column called FullName.
File content before running the script:
FirstName | LastName |
Vignesh | Krishnakumar |
Nandhini | Vignesh |
Sampath | Charlu |
Vyapini | Vignesh |
Krishnakumar | Sankaran |
Durga | Krishnakumar |
Code:
#Reading the csv by importing
$CSV = import-csv "C:\Users\R003646\Desktop\Sample.csv" | select FirstName,LastName,
@{n='FullName';e={$_.FirstName + " " + $_.LastName}}
# script @{n='FullName";e={$_.FirstName + " " + $_.LastName}} will create the new column FullName and concatenate the FirstName and LastName Column Value
# Export the data from the Variable $CSV to the new file
$CSV | export-CSV "C:\Users\R003646\Desktop\Sample.csv"
Output:
Example #9
Here we will see how joining two or more paths generates a single path. The Join-Path cmdlet combines two or more paths into a single path.
Syntax:
NAME
Join-Path
SYNTAX
Join-Path [-Path] <string[]> [-ChildPath] <string> [-Resolve] [-Credential <pscredential>] [-UseTransaction] [<CommonParameters>]
ALIASES
None
Example #10
Input:
Write-Host "Welcome to Join Path example"
$path1= "C:\test"
$path2="D:\test"
$path3= "E:\test"
$path4="F:\test"
$path5="G:\test"
Write-Host "Appending new path"
Join-Path -Path $path1, $path2, $path3, $path4, $path5 -ChildPath test1
Output:
Other Commonly used String Functions
1. Split()
This is another method that can be used to split a string into substrings.
Syntax:
.Split(strSeparator [, MaxSubstrings] [, Options])
String -Split strSeparator [, MaxSubstrings] [, Options]
String -Split {scriptblock} [, MaxSubstrings]
-Split String
- strSeparator: It is the character of identification to split the string
- MaxSubstrings: The maximum number of substrings that can be generated
Example:
Write-Host "Generating substring using split method"
$teststring="My name is Joseph- am from UK"
Write-Host "splitting using - character"
$teststring -split "-"
$teststring="domainname\username"
Write-Host "Splitting using \ character"
$teststring -split "\\"
Write-Host "generating substring using space"
$string="string1 string2 strin3"
$string.Split("")
Write-Host "splitting using multiple separators"
$string="domain\systems-test"
$string.Split("\\").Split("-")
Output:
2. Replace Function
When it comes to a string, replacing a part of a string or substring is an integral operation. It is always required by PowerShell users to find a text and replace it with some other piece of text. This is achieved by the Replace() method.
Syntax:
Replace(strOldChar, strNewChar)
Stroldchar: Character to be found
Strnewchar: character to be replace the found text
Example:
Code:
Write-Host "Replacing a text in string"
$test="Old text to be replaced"
Write-Host "Going to replace old"
$test.Replace("old","New")
Write-Host "Text is replaced"
Output:
Conclusion – PowerShell Concatenate String
The article covers string concatenation in detail. It demonstrates the various ways in which strings can be combined other than the “+” operator. Also demonstrates various examples of how a string concatenation can be achieved. It also covers various string methods like string concatenation, string comparison, string replacement, etc.
Frequently Asked Questions (FAQs)
Q1. What is the possible way to concatenate the strings in PowerShell?
Answer: Access the ‘PowerShell ISE initially with administrator privileges. To do the same, go to the search bar to find “PowerShell ISE“. After getting the search result, right-click on the ‘PowerShell ISE’ application, and select ‘Run as administrator’.
Q2. How to replace a string in PowerShell?
Answer: In PowerShell, it is easy to replace the existing string with the new string using a simple replace() operator. The compiler doesn’t find any preferred string; it doesn’t respond to anything.
Q3. How to represent variables in PowerShell?
Answer: Variables are the data-storing units. In PowerShell, variables simply represent a text string that starts with a dollar sign. For example, $text, $value, etc.
Recommended Articles
We hope that this EDUCBA information on “PowerShell Concatenate String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.