Updated March 4, 2023
Introduction to PowerShell SubString
One of the most frequently performed operation or requirement with any language is the manipulation of strings. String functions are an integral part of PowerShell and there are various functions present to handle the string manipulation related tasks. In PowerShell, everything is an object and string is also an object of type System. String. A string is nothing, but a collection of characters enclosed within a single quote (‘’) or a double quote (“”). Substring is the part of any string or substring is nothing but a subset of a string. This article will cover in-depth about string in PowerShell, various functions that are available related to string operations, substrings, functions related to substring. The substring () is used to extract a part of a string and it is available for every string object in PowerShell.
Operations available on a string object:
Before looking at the substring(), let’s see the list of operations that are available for any string object.
Input:
Write-Host "Welcome to string example"
$test="this is a string variable"
Write-Host "below are the available operations available on string object"
$test | Get-Member
Output:
As you can see from the above, substring is one of the functions. There are more than 50 string operations available.
Some of the most commonly used operations are StartsWith, Remove, Split, Replace, Rim. The following is an example.
Example of PowerShell SubString
Input:
Write-Host "Welcome to string example"
$test="this is a string variable a"
Write-Host "Example of starts with"
$test.StartsWith("t")
Write-Host "Example of replace"
$test.Replace("is","was")
Write-Host "Trim demo"
$test.TrimEnd("a")
Write-Host "To Upper"
$test.ToUpper()
$test="A B C D E F"
Write-Host "to lower"
$test.ToLower()
$test="this is a string variable a"
Write-Host "Example of starts with"
$test.StartsWith("t")
Write-Host "Example of replace"
$test.Replace("is","was")
Write-Host "Trim demo"
$test.TrimEnd("a")
Write-Host "To Upper"
$test.ToUpper()
$test="A B C D E F"
Write-Host "to lower"
$test.ToLower()
Output:
-
Substring:
Syntax:
.Substring( StartIndex [, length] )
- StartIndex: The position of the string from which the substring must be started. Usually, it should be 0 or greater than that and less than the length of the string.
- Length: The length of the substring.
Use:
Used to fetch a portion of a string.
Example:
Input:
Write-Host "sample of substring function"
$test="am vignesh krishnakumar"
Write-Host "Extracting only first two letters"
$test.Substring(0,2)
Write-Host "Printing the length of the string"
$test.Length
write-host "extracting middle word"
$test.Substring(2,7)
Write-Host "Extracting the last word"
$test.Substring(10,7)
Output:
-
String concatenation:
In some cases, it is required to combine two strings. That is done with the help of ‘+’ operator.
Eg:
Write-Host "String concatenation demo"
$string1="first sentence of the tutorial"
Write-Host "GOing to combine the first sentence with the new one"
$string2="Second sentence to be concatenated"
Write-Host "GOing to combine the third sentence with the new one"
$string3= $string1 + $string2
write-host "Concatenated string is below"
$string3
Output:
While concatenating a string and a number, it is advisable that the first variable is a string and not a number. The below example shows what will happen if the first variable is an integer.
Input:
Write-Host "String concatenation demo of int and string"
$string1=43
$string2="my name is vignesh"
$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=43
$string2="my name is vignesh"
$string3=$string2 + $string1
Write-Host $string3
Output:
Other commonly used string functions:
-
.Split():
The 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 character of identification to split the string
- MaxSubstrings: The maximum number of substrings that can be generated
Example:
Input:
Write-Host "generating substring using split method"
$teststring="my name is vignesh- am from chennai"
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:
Example:
Input:
This example will show how to split and generate substring based on regex and to split MAC addresses.
Write-Host "split using regex"
$test=" this . is an . example . of an was an and an . . . ."
$test.Split("an")
Write-Host "splitting a mac address"
$test="12-23-AB-DE-45-BC"
$test.Split("-")
Write-Host "Splitting an IP Address"
$test="122.43.56.78"
$test.Split(".")
Output:
-
Replace function:
When it comes to string, replacing a part of a string or substring is an integral operation. Always it is 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:
Input:
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:
Example:
Write-Host "Replacing a multiple text"
$string="my name is billa, vazhaikai elam naanum super"
$string-replace "vazhikai", "replaced" -replace "elam", "All"
Write-Host "Replacing a text in a file"
(Get-Content -path C:\Users \Desktop\test.txt -Raw) -replace 'was','is'
Write-Host "text in the file is replaced"
Output:
-
Comparison of strings:
The final method that we are going to see is the string comparison method. Most cases, it is required to compare strings and check if they are equal. This is done using the string compare method.
Example:
Input:
Write-Host "Welcome to string comparison"
$test=" STRING DEMO"
$test1="string demo"
Write-Host "Comaprison using equal method"
$test.Equals($test1)
$test.ToLower.Equals($test1)
$test.Equals($test1,1)
Write-Host "Comaprison using comaprison method"
$test.CompareTo($test1)
Output:
Conclusion
Thus, the article covered string operations and substring in detail. It covered in detail the substring method in PowerShell, along with various methods of extracting a substring from a string in different ways. It also covered various string methods like string concatenation, string comparison, string replace, etc. The best way to learn more about this would be to try other various methods and practice them in sample scripts.
Recommended Articles
This is a guide to PowerShell SubString. Here we discuss the Introduction, list of operations, and examples with code implementation respectively. You may also have a look at the following articles to learn more –