Master PowerShell Strings: Concatenate, Split & More

Published:1 April 2020 - 15 min. read

Strings in PowerShell are probably the most used data type in PowerShell. From displaying messages, prompting for input, or sending data to files, it is almost impossible to write scripts without strings being involved.

Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.

In this article, you’ll learn that strings are not just for reading and displaying. They can also be manipulated to fit the purpose of whatever task you may be writing the script for. Like, replacing characters or entire words, concatenating strings to form a new string, or even splitting one string into multiple strings.

Understanding Strings

According to the .NET definition of string – “A string is a sequential collection of characters that is used to represent text”. In summary, as long as there’s a sequence of characters forming a text, there’s a string.

Defining System Strings in PowerShell

Strings are defined by enclosing a series of characters in single or double-quotes. Below are examples of a string.

PS> 'Hello PowerShell - Today is $(Get-Date)'PS> "Hello PowerShell - Today is $(Get-Date)"

Strings are actually System.Strings in .NET.

As you can see from the example above, the first string is enclosed with a single quote, and the second string is enclosed in a double-quote. If you’re wondering, the only difference between the two is that strings in double quote support string expansion, while a single quote will only represent literal strings.

To confirm the single-quote vs. double-quote concept, when you paste both strings from the example above in PowerShell.

The screenshot below shows that a single-quoted string returns the exact literal string that was defined. While the double-quoted string returns the string with the expression result of the Get-Date cmdlet.

Single Quote vs. Double-Quote String Output
Single Quote vs. Double-Quote String Output

The result shown above demonstrates the distinction of when it is appropriate to use single or double quotes when defining strings.

The String Object

As stated in the previous section, the collection of characters that form a text is a string. The resulting value of the string is the String object. The String object is a .NET object that is of the [System.String] type.

And since System.String is an object, it has properties that you can access using the Get-Member cmdlet. Below we’re inserting a variable inside of a string with double-quotes.

PS> "Hello PowerShell - Today is $(Get-Date)" | Get-Member=

The screenshot below shows the TypeName and the partial list of properties of the String object.

String Object properties
String Object properties

Concatenating PowerShell Strings

String concatenation is described as joining two or more strings together, essentially creating one string object from multiple separate string objects. There are several methods in PowerShell concatenate strings. Each method is different, and whichever one to use depends on how you plan to implement string concatenation.

A typical example of using string concatenation in the real world is Active Directory user creation. Perhaps you’re creating a user creation script that takes the first name, last name, and department values from a list.

Using string concatenation, you can formulate the standard naming convention for the name, display name, username, and email address. For this example, you’ll be working with the strings shown below. Copy this code below and paste it in your PowerShell session.

$domain = 'contoso.com'
$firstname = 'Jack'
$lastname = 'Ripper'
$department = 'Health'

Using the sample variable values above, the goal is to derive the following values listed below by concatenating strings together.

  • Name = firstname lastname
  • DisplayName = firstname lastname (department)
  • SamAccountName = firstname.lastname
  • EmailAddress = [email protected]

In the next sections, the values listed above will be created using the different string concatenation methods available in PowerShell.

Let’s begin!

Using the PowerShell Strings Concatenation Operator

Programming languages have their own string concatenation operator used for concatenating strings. For example, in Visual Basic, the concatenation method is the ampersand sign (&). PowerShell also has its own concatenation method, which is the plus sign (+).

Using the string concatenation operator, you can concatenate strings using the code below.

## Name
$firstname + ' ' + $lastname
## DisplayName
$firstname + ' ' + $lastname + ' (' + $department + ')'
## SamAccountName
$firstname + '.' + $lastname
## Email Address
$firstname + '.' + $lastname + '@' + $domain

Using the PowerShell Strings Expansion

The use of string expansion might be the method that results in the shortest code when concatenating strings. You’ll see from the code below that all that is needed is to arrange the strings as they should appear and enclose them inside double-quotes.

# Using String Expansion
## Name
"$firstname $lastname"
## DisplayName
"$firstname $lastname ($department)"
## SamAccountName
"$firstname.$lastname"
## Email Address
"$firstname.$lastname@$domain"

Then, PowerShell interprets and handles the string expansion inside the double quotes string to output the concatenated string as a result. You can refer to the sample output below.

Using String Expansion
Using String Expansion

Using the PowerShell Format Operator

The format operator (-f) is mostly used for composite formatting. What’s important to remember is that with this method, there are three parts to using -f.

Refer to the third line of the code below. The "{0} {1}" represents the format and placeholders. The numbers in the curly brackets indicate the index of the string in the collection to display in its place. The quotes can be single or double quotes.

The collection of string as input in this example is represented by $firstname,$lastname. This means that the index of the $firstname variable is 0, while the $lastname is 1.

Finally, -f is the place in between the placeholder and the collection of strings represented by (-f).

## Name
"{0} {1}" -f $firstname,$lastname
## DisplayName
"{0} {1} ({2})" -f $firstname,$lastname,$department
## SamAccountName
"{0}.{1}" -f $firstname,$lastname
## Email Address
"{0}.{1}@{2}" -f $firstname,$lastname,$domain

The code above will result in the results shown below.

Using the Format Operator
Using the Format Operator

Using the PowerShell -Join Operator

The -Join operator can be used to join strings into a single string in two ways.

The first way to use -Join is by following it with the array of strings that you want to concatenate. The -Join operator does not provide an option to add a delimiter. All the strings in the array will be glued together with nothing in between.

-Join <String[]>

The second way to use the -Join operator is to specify the delimiter to be used. The array of strings will be joined together, but the specified delimiter character will be inserted in between each string.

<String[]> -Join <Delimiter>

Going back to the goal of concatenating strings, the code below demonstrates how to use the -Join operator for putting together strings.

## Name
$firstname, $lastname -join ' '
## DisplayName
$firstname,$lastname,"($department)" -join ' '
## SamAccountName
-join ($firstname,'.',$lastname)
## Email Address
-join ($firstname,'.',$lastname,'@',$domain)

When you run the example code above in PowerShell, you would expect to see a similar output to the one shown below.

Using the PowerShell Join Operator
Using the PowerShell Join Operator

The .NET String.Format() Method

The .NET String.Format method is the .NET counterpart of the PowerShell Format Operator.  It operates the same as the format operator where the format and the placeholders need to be specified.

## Name
[string]::Format("{0} {1}",$firstname,$lastname)
## DisplayName
[string]::Format("{0} {1} ({2})",$firstname,$lastname,$department)
## SamAccountName
[string]::Format("{0}.{1}",$firstname,$lastname)
## Email Address
[string]::Format("{0}.{1}@{2}",$firstname,$lastname,$domain)

The screenshot below shows the String.Format Method in action.

Using the .NET String.Format Method
The .NET String.Format Method

The .NET String.Concat() Method

Another method to concatenate strings is to use the .Net String.Concat Method. The .NET String.Concat Method is the .NET counterpart of the PowerShell String Concatenation Operator (+). But, instead of using the + sign to join strings, you can add all the strings inside the method like this – [string]::Concat(string1,string2...).

## Name
[string]::Concat($firstname,' ',$lastname)
## DisplayName
[string]::Concat($firstname,' ',$lastname,' (',$department,')')
## SamAccountName
[string]::Concat($firstname,'.',$lastname)
## Email Address
[string]::Concat($firstname,'.',$lastname,'@',$domain)

The screenshot below demonstrates the result of invoking the .NET String.Concat method. You can see that PowerShell has merged string1, string2.

Using the .NET String.Concat Method
Using the .NET String.Concat Method

The .NET String.Join() Method

The .NET String.Join method is the .NET method counterpart of the PowerShell Join Operator (-join). The format for this method is [string]::Join(<delimiter>,<string1>,<string2>,...).

The first item inside the -Join method is always the delimiter. Then, the succeeding item values are the strings you want to concatenate. See the example code below. Remember, the first item is always the delimiter. If you do not want to add a delimiter, the you can specify this —> ''.

## Name
[string]::Join(' ',$firstname,$lastname)
## DisplayName
[string]::Join(' ',$firstname,$lastname,"($department)")
## SamAccountName
[string]::Join('',$firstname,'.',$lastname)
## Email Address
[string]::Join('',$firstname,'.',$lastname,'@',$domain)
Using the .NET String.Join Method
The .NET String.Join Method

Splitting PowerShell Strings

You’ve seen several different methods to concatenate strings in the previous section. In this section, you’ll learn about the different ways to use PowerShell to split strings. Splitting strings is the reverse action of concatenation.

You can split strings in PowerShell two different ways – the split() function/method or the split operator.

Splitting Strings with the Split() Method

If you’re looking for a simple way to split a string to create an array, look no further than the split() method. The split() method is on every string object and is capable of splitting a string into an array based on a non-regex character.

For example, if you have a string like green|eggs|and|ham and you’d like to create an array like @('green','eggs','and','ham'), you can split this string on the pipe symbol (|) like in the following code snippet.

$string = 'green|eggs|and|ham'
$string.split('|')

You’ll then see that PowerShell split the string in the desired array with the pipe symbol.

The split() method is a simple way to split strings but is limited. The split() method does not allow splitting strings via regular expressions. If you need more advanced capabilities to split a string, you’ll need to learn about the split operator.

The -split Operator

The main operator that can be used for splitting strings in PowerShell is the -Split operator. Using the -Split operator, strings are split between whitespaces by default, or with specific delimiting characters.

Below is the -Split operator syntax for your reference. Remember to note the difference between the unary and binary split.

# Unary Split
-Split <String>
-Split (<String[]>)

# Binary Split
<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]]
<String> -Split {<ScriptBlock>} [,<Max-substrings>]

In this example, the $string variable holds the value of a single line string. Then, with the -Split operator, the single line string will be split into a PowerShell string array. The resulting split string is saved to the $split variable.

## Splitting Strings into Substrings
# Assign a string value to the $string variable
$string = 'This sentence will be split between whitespaces'
# Split the value of the $string and store the result to the $split variable
$split = -split $string
# Get the count of the resulting substrings
$split.Count
# Show the resulting substrings
$split

As you can see from the result above, what was originally a single string was split into 7 substrings. It demonstrates how PowerShell split a string into an array.

The Character Delimiter

In the previous example, the -Split operator split the single string object into multiple substrings even without specifying a delimiter; that is because the -Split operator’s default delimiter is  whitespace. But, delimiters can also be characters, strings, patterns, or script blocks.

In this example, the delimiter used is the semicolon ;.

## Splitting Strings into Substrings with Delimiter
# Assign a string value to the $string variable
$string = 'This;sentence;will;be;split;between;semicolons'
# Split the value of the $string and store the result to the $split variable
$split = $string -split ";"
# Get the count of the resulting substrings
$split.Count
# Show the resulting substrings
$split

When you test the above code in PowerShell, you’ll get this result below.

Splitting a String into Substrings with Character Delimiter
Splitting a String into Substrings with Character Delimiter

You notice from the above output that the delimiter character was omitted altogether from the resulting substrings.

If, for some reason, that you need to retain the delimiter character, the delimiter can be retained by enclosing the character in a parenthesis.

$split = $string -split "(;)"
$split.Count
$split

After modifying the split delimiter, as shown above, running it would result in the output shown below.

Splitting a string on semicolon
Splitting a string on semicolon

The result above shows that the delimiter characters are not omitted, and are counted into the resulting substrings.

The String Delimiter

Strings can also be split by another string as the delimiter. In this example, the string “day” is used as the delimiter.

$daysOfTheWeek= 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek -split "day"

The Script Block Delimiter

A scriptBlock as the delimiter enables the -Split operator to perform custom or complex splitting of strings.

In the previous examples, the delimiter character or string is used to split the strings. With the use of a script block, you can create an expression that effectively uses more than one delimiter.

The example below uses the expression {$PSItem -eq 'e' -or $PSItem -eq 'y'} which means that the string will be split if the incoming character is 'e' or 'a'.

$daysOfTheWeek= 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek -split {$PSItem -eq 'e' -or $PSItem -eq 'y'}

And when you run this command above, the output will be substrings that are split with the delimiter characters inside specified in the expression in the script block.

Splitting a String into Substrings with a Script Block Delimiter
Splitting a String into Substrings with a Script Block Delimiter

This next example does a little bit more with a script block. This time, the expression evaluates whether:

  • The incoming character passes as an integer; and
  • That its value higher than 1

If the result of the evaluation is true, then the -Split operator will use that character as a delimiter. Also, error handling is added to ensure that the errors are filtered out.

$daysOfTheWeek= 'monday1tuesday2wednesday3thursday1friday4saturday8sunday'
$daysOfTheWeek -split {
    try {
        [int]$PSItem -gt 1
    }
    catch {
        #DO NOTHING
    }
}

After running the code shown above, the expectation is that the string will be split at the place where the character value can be cast as an integer with a value higher than 1. The below shows the expected output.

Splitting a String into Substrings with a Script Block Delimiter
Splitting a String into Substrings with a Script Block Delimiter

The RegEx Delimiter

By default, the -Split operator uses RegEx matching the specified delimiter. This means that you can also use RegEx as delimiters for splitting strings.

In this next example, the string contains word characters and non-word characters. The goal is to split the string with any non-word characters. In RegEx, non-word characters are represented by \W, while word characters that matches these characters – [a-zA-Z0-9_] are represented by \w.

$daysOfTheWeek= 'monday=tuesday*wednesday^thursday#friday!saturday(sunday'
$daysOfTheWeek -split "\W"

Limiting Substrings

It is also possible to stop the -Split operator from splitting a string to a number of substrings. The option that can be used to achieve limiting the substring result is the <Max-substrings> parameter.

When you refer back to the -Split syntax, the <Max-substrings> parameter is the parameter that directly follows the <Delimited> parameter. The syntax is shown again below for reference.

<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]]

Following the syntax above, the example code below is modified to limit the number of split/substrings to 3.

$daysOfTheWeek= 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek -split ",",3

And, running the code above results to this output below. As you can see from the output below, the string was split into three substrings only. The remaining delimiters were skipped.

Limiting the Number of Substrings starting from the first 3 matched delimiters
Limiting the Number of Substrings starting from the first 3 matched delimiters

Now, if you want to limit the substrings, but in reverse, you could change the <Max-substrings> parameter value to a negative value. In this next example, the <Max-substrings> is changed to -3.

$daysOfTheWeek= 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek -split ",",-3

And as a result of the modified code above, the string was split starting from the last three matched delimiters.

Limiting the Number of Substrings starting from the last 3 matched delimiters
Limiting the Number of Substrings starting from the last 3 matched delimiters

Finding and Replacing Strings

In this section, you will learn about the two methods that can be used to search for and perform a PowerShell string replace. The Replace() method and the -Replace operator.

The Replace() Method

The string object also has a built-in method that could help perform search and replace operations – the replace() method. The replace() method takes a maximum of four overloads.

The acceptable set of overloads for the replace() method is listed below.

<String>.Replace(<original>, <substitute>[, <ignoreCase>][, <culture>])

The only required overloads that are the <original> and <substitute>. The <ignoreCase>and <culture> are optional.

In the example below, the code will search all the instances of the comma (,) character with a semi-colon (;).

$daysOfTheWeek = 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek.Replace(',',';')

Aside from replacing just a single character, you can also use the replace() method to search and replace strings. The example code below replaces the word “day” with “night”.

$daysOfTheWeek = 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek.Replace('day','NIGHT')
Replacing a matched string using the replace() method
Replacing a matched string using the replace() method

The -Replace Operator

The syntax for the replace operator is shown below.

<string> -replace <original>, <substitute>

Using the syntax above, the example code below replaces the word “day” with “Night” with the -replace operator.

$daysOfTheWeek = 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek -replace 'day','NIGHT'
Replacing a matched character using the -replace operator
Replacing a matched character with the -replace operator

This next example uses a RegEx match to replace strings with the -replace operator. The code below searches the here-string for the string that matches (#. ) and replace them with nothing.

$daysOfTheWeek = @'
1. Line 1
2. Line 2
3. Line 3
4. Line 4
5. Line 5
'@
$daysOfTheWeek -replace "\d.\s",""
Replacing a RegEx match using the -replace operator
Replacing a RegEx match using -replace

Extracting Strings from Strings

The string object has a method called SubString(). The SubString() method is used to extract strings within strings at specific locations. The syntax for the SubString() method is shown below.

<String>.SubString(<startIndex>[,<length>])

The startIndex in the position index where the SubString() method would start the search. The length parameter indicates the number of characters to return starting from the startIndex. The length parameter is optional, and if it is not used, the SubString() method will return all characters.

Extracting a Substring from a Starting Position and a Fixed Length

The example code below retrieves the part of the $guid string value starting from the index 9 and return exactly the 5 characters that follow.

$guid = 'e957d74d-fa16-44bc-9d72-4bea54952d8a'
$guid.SubString(9,5)

Extracting a Substring from a Dynamic Starting Position

This next example demonstrates how you can use the PowerShell string length property to dynamically define a starting index.

The code below does the following:

  • Gets the length of the string object.
  • Gets the index of the middle index by dividing the length by 2.
  • Uses the the middle index as the starting index of the substring.
$guid = 'e957d74d-fa16-44bc-9d72-4bea54952d8a'
$guid.SubString([int]($guid.Length/2))

Since the length value was not specified, the Substring() method returned all the characters from the starting index.

Extracting a Substring from a Dynamic Starting Position
Extracting a Substring from a Dynamic Starting Position

Comparing PowerShell Strings

You can use PowerShell to compare strings too using the string object’s built-in methods like the CompareTo(), Equals(), and Contains() methods. Or, by using the PowerShell  comparison operators.

Using the CompareTo() Method

The CompareTo() method returns a value of 0 if the two strings are of the same value. For example, the code below compares two string objects.

$string1 = "This is a string"
$string2 = "This is a string"
$string1.CompareTo($string2)

And since the values are the same, the result should be 0, as shown below.

Using CompareTo() method to compare strings
Using CompareTo() method to compare strings

Using the Equals() Method and -eq

The Equals() method and the -eq operator can be used to check if the value of the two strings is equal.

The example below uses the Equals() method to compare the values of $string1 and $string2.

$string1 = "This is a string"
$string2 = "This is not the same string"
$string1.Equals($string2)

The code above should return False because the values of $string1 and $string2 are not equal to one another.

Comparing strings using the Equals() method
Comparing strings with the Equals() method

The next example code below uses -eq instead to compare the values of $string1 and $string2.

$string1 = "This is a string"
$string2 = "This is not the same string"
$string1 -eq $string2

As you can see from the output below, the result when using -eq and the Equal() method are the same.

Comparing strings using the -eq operator
Comparing strings with the -eq operator

Using the Contains() Method

In this example, the two strings are being compared by checking if the PowerShell string contains  the substring of another string.

The code below shows that $string1 and $string2 values are not equal. However, the value of $string2 is a substring of $string1.

$string1 = "This is a string 1"
$string2 = "This is a string"
$string1.Contains($string2)

The result of the code above should be True, as shown below.

Comparing strings using the Contains() method
Comparing strings using the Contains() method

Further Reading

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!