---
title: "Master PowerShell Strings: Concatenate, Split & More"
description: "Discover the power of PowerShell strings manipulation, from concatenation to splitting, and level up your scripting skills."
canonical: "https://adamtheautomator.com/powershell-strings/"
---

# Master PowerShell Strings: Concatenate, Split & More

> Discover the power of PowerShell strings manipulation, from concatenation to splitting, and level up your scripting skills.

Source: https://adamtheautomator.com/powershell-strings/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Master PowerShell Strings: Concatenate, Split & More](https://adamtheautomator.com/wp-content/uploads/2020/04/allison-cochrane-B64EVHorNz0-unsplash.jpg)

# Master PowerShell Strings: Concatenate, Split & More

[![](https://secure.gravatar.com/avatar/9a14f10ff1b1ec7d790d34f5b559e4d3de2d31b172e6ef266dfd8b479174d97b?s=192&d=mm&r=g)June Castillote](https://adamtheautomator.com/author/june/)1 April 202014 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[PowerShell](/tag/powershell/)

Table of Contents

*   [Understanding Strings](#understanding-strings)
*   [Defining System Strings in PowerShell](#defining-a-string)
*   [The String Object](#the-string-object)
*   [Concatenating PowerShell Strings](#concatenating-strings)
*   [Using the PowerShell Strings Concatenation Operator](#using-the-powershell-string-concatenation-operator)
*   [Using the PowerShell Strings Expansion](#using-the-powershell-string-expansion)
*   [Using the PowerShell Format Operator](#using-the-powershell-format-operator)
*   [Using the PowerShell -Join Operator](#using-the-powershell-join-operator)
*   [The .NET String.Format() Method](#using-the-net-string-format-method)
*   [The .NET String.Concat() Method](#using-the-net-string-concat-method)
*   [The .NET String.Join() Method](#using-the-net-string-join-method)
*   [Splitting PowerShell Strings](#splitting-strings)
*   [Splitting Strings with the Split() Method](#splitting-strings-with-the-split-method)
*   [The -split Operator](#the-split-operator)
*   [The Character Delimiter](#splitting-strings-using-a-character-delimiter)
*   [The String Delimiter](#splitting-strings-using-a-string-delimiter)
*   [The Script Block Delimiter](#splitting-strings-using-a-script-block-delimiter)
*   [The RegEx Delimiter](#splitting-strings-using-a-regex-delimiter)
*   [Limiting Substrings](#splitting-strings-and-limiting-the-number-of-substrings)
*   [Finding and Replacing Strings](#find-and-replace-strings)
*   [The Replace() Method](#using-the-replace-method)
*   [The -Replace Operator](#using-the-replace-operator)
*   [Extracting Strings from Strings](#extracting-strings-from-strings)
*   [Extracting a Substring from a Starting Position and a Fixed Length](#extracting-a-substring-from-a-starting-position-and-a-fixed-length)
*   [Extracting a Substring from a Dynamic Starting Position](#extracting-a-substring-from-a-dynamic-starting-position)
*   [Comparing PowerShell Strings](#comparing-strings)
*   [Using the CompareTo() Method](#using-the-compareto-method)
*   [Using the Equals() Method and -eq](#using-the-equals-method-and-the-eq-operator)
*   [Using the Contains() Method](#using-the-contains-method)
*   [Further Reading](#further-reading)

Strings in PowerShell are probably the most used data type in [PowerShell](https://adamtheautomator.com/tag/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.

```powershell
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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132626.335.png)

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\]](https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.8#CultureSensitive)_ 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.

```powershell
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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132639.040.png)

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](https://adamtheautomator.com/tag/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.

```powershell
$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 = _[firstname.lastname@contoso.com](mailto:firstname.lastname@contoso.com)_

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.

```powershell
## 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.

```powershell
# 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132701.315.png)

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`).

```powershell
## 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132711.468.png)

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.

```powershell
-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.

```powershell
<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.

```powershell
## 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132721.152.png)

Using the PowerShell Join Operator

### The .NET `String.Format()` Method

The _[.NET String.Format method](https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8)_ 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.

```powershell
## 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132731.089.png)

The .NET String.Format Method

### The .NET `String.Concat()` Method

Another method to concatenate strings is to use the [_.Net String.Concat Method_](https://docs.microsoft.com/en-us/dotnet/api/system.string.concat?view=netframework-4.8). 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...)`.

```powershell
## 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132740.561.png)

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 —> `''`.

```powershell
## 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132749.826.png)

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.

```powershell
$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.

```powershell
# 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.

```powershell
## 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](https://en.wikipedia.org/wiki/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 `;`.

```powershell
## 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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132822.804-1024x525.png)

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.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T132832.043.png)

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.

```powershell
$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'`.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/split03-1.gif)

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.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/split04-1.gif)

Splitting a String into Substrings with a Script Block Delimiter

### **The RegEx Delimiter**

By default, the `-Split` operator uses _[RegEx](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-7)_ 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`.

```powershell
$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](https://adamtheautomator.com/powershell-substring/ "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.

```powershell
<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.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/split06-1-1024x207.gif)

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`.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/split07-1-1024x207.gif)

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.

```powershell
<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 (`;`).

```powershell
$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”.

```powershell
$daysOfTheWeek = 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek.Replace('day','NIGHT')
```

![Replacing a matched string using the replace() method](https://adamtheautomator.com/wp-content/uploads/2020/05/replace02-1-1024x144.gif)

Replacing a matched string using the `replace()` method

### The `-Replace` Operator

The syntax for the replace operator is shown below.

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

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

```powershell
$daysOfTheWeek = 'monday,tuesday,wednesday,thursday,friday,saturday,sunday'
$daysOfTheWeek -replace 'day','NIGHT'
```

![Replacing a matched character using the -replace operator](https://adamtheautomator.com/wp-content/uploads/2020/05/replace03-1-1024x144.gif)

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](https://devblogs.microsoft.com/scripting/powertip-use-here-strings-with-powershell/)_ for the string that matches (`#.` ) and replace them with _nothing_.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/replace04-1.gif)

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.

```powershell
<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.

```powershell
$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.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/substring02-1.gif)

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](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7)_.

### 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.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/compare01-1.gif)

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`.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/compare02-1.gif)

Comparing strings with the `Equals()` method

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

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/compare03-1.gif)

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`.

```powershell
$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](https://adamtheautomator.com/wp-content/uploads/2020/05/compare04-1.gif)

Comparing strings using the `Contains()` method

## Further Reading

*   [**_Learn the PowerShell string format and expanding strings_**](https://adamtheautomator.com/powershell-string-format/)
*   [**_Back to Basics: Understanding PowerShell Objects_**](https://adamtheautomator.com/powershell-objects/)
*   [**_Understanding PowerShell and Basic String Formatting_**](https://devblogs.microsoft.com/scripting/understanding-powershell-and-basic-string-formatting/)
*   [**_About Quoting Rules_**](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)
*   [**_String Class_**](https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.8#CultureSensitive)
*   [**_About\_Join_**](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_join?view=powershell-7)
*   **_[About Regular Expressions](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-7)_**

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-strings%2F&text=Master%20PowerShell%20Strings%3A%20Concatenate%2C%20Split%20%26%20More)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-strings%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-strings%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2026/06/26995-troubleshoot-dns-issues-powershell-codex.webp)

### [Troubleshoot DNS Issues with PowerShell](/troubleshoot-dns-issues-powershell/)

Troubleshoot DNS issues with PowerShell by testing name resolution, DNS client settings, cache entries, and network connectivity in a repeatable workflow.

![](https://adamtheautomator.com/wp-content/uploads/2025/10/image_2025-10-24_095322075.png)

### [Migrating from PowerShell 6 to 7.5: Breaking Changes/New Features](/migrating-powershell-6-to-7-5/)

Migrate from PowerShell Core 6 to 7.5: breaking changes, features, and testing tips.

![](https://adamtheautomator.com/wp-content/uploads/2025/06/featured-image-6.png)

### [How to Add Timeouts to Pester Tests with PowerShell Runspaces](/pester-test-timeout-runspaces/)

Prevent Pester tests from hanging indefinitely using PowerShell runspaces. Learn to handle variable scoping, module loading, TestDrive access, and stream capture challenges with timeout protection.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
