Back to Basics: PowerShell Strings

June Castillote

June Castillote

Read more posts by this author.

The string data type is 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.

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 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 a String

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)"

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 String is an object, it has properties that you can access using the Get-Member cmdlet.

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

  • 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 in available in PowerShell.

Let’s begin!

Using the PowerShell Strings Concatenation Operator

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

Using the string concatenation operator, you can derive the needed values using the code below.

# Using the String Concatenation Operator
## Name
$firstname + ' ' + $lastname
## DisplayName
$firstname + ' ' + $lastname + ' (' + $department + ')'
## SamAccountName
$firstname + '.' + $lastname
## Email Address
$firstname + '.' + $lastname + '@' + $domain

The code above will result in the output shown below.

Using the String Concatenation Operator
Using the String Concatenation Operator

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
"[email protected]$domain"

Then, PowerShell interprets and handles the string expansion 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 the format operator.

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 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, the format operator is place in between the placeholder and the collection of strings represented by (-f).

# Using Format Operator
## 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 multiple 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. This method of using -Join 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 -Join allows you 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.

# Using the Join Operator
## 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

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

# Using the Format Method
## 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
Using the .NET String.Format Method

Using the .NET String.Concat() Method

Another method to concatenate strings is using 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...).

# Using the .NET String.Concat Method
## 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 using the .NET String.Concat method

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

Using the .NET String.Join() Method

The .NET String.Join method is the .NET method counterpart of the PowerShell Join Operator (-join). The format for using 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 —> ''.

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

The result of using the .NET String.Join method is shown below.

Using the .NET String.Join Method
Using 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 – using the split() function/method or using 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 using the pipe symbol.

Splitting a string using the split method
Splitting a string using the split method

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, using 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

The output of the above command is demonstrated below.

Splitting a string into substrings
Splitting a string into substrings

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.

Splitting Strings using a 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.

Splitting Strings using a String Delimiter

Strings can also be split using 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 expected result is that the string will be split between the text “day”, as shown below.

Splitting a String into Substrings using a String Delimiter
Splitting a String into Substrings using a String Delimiter

Splitting Strings using a Script Block Delimiter

Using 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 using 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

Splitting Strings using a 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 using 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"

The code above will result in this output below. As you can see, any non-word characters found in the string was used as a delimiter.

Splitting a String into Substrings with a RegEx Delimiter
Splitting a String into Substrings with a RegEx Delimiter

Splitting Strings and Limiting the Number of 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

Find and Replace 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.

Using 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(',',';')
Replacing a matched character using the replace() method
Replacing a matched character using the replace() method

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

Using the -Replace Operator

Another way to do a search and replace operation on strings is by using 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” using 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 using the -replace operator

This next example uses a RegEx match to replace strings using 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 the -replace operator

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)

Refer to the demonstration below to see how the output of the code above would look like.

Extracting strings from a starting index with length
Extracting strings from a starting index with length

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 the -eq Operator

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 using the Equals() method

The next example code below uses the -eq operator 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 the -eq operator and the Equal() method are the same.

Comparing strings using the -eq operator
Comparing strings using 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

Conclusion

In this article, you’ve learned about one of the most used objects in PowerShell – the string. You’ve learned how to manipulate strings in such a way that it can be concatenated, split, or replaced. There were also demonstrations of the ways to compare strings.

There are other methods built-in to the string object that wasn’t covered here. Not because they are not important, but because they are simple enough that you should be able to figure out their use.

One of these other methods that I recommend for you to check on your own is how to use PowerShell to trim strings using the Trim(), TrimStart(), and the TrimEnd() methods.

The example provided here attempts to convey the basics of working with strings. In turn, it is my hope that the knowledge you gained here will enable you to look at using strings more closely whenever you’re writing code.

Further Reading

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!