EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PowerShell SubString

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » PowerShell Tutorial » PowerShell SubString

PowerShell SubString

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:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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:

PowerShell SubString 1

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

Output:

PowerShell SubString 2

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

Popular Course in this category
Shell Scripting Training (4 Courses, 1 Project)4 Online Courses | 1 Hands-on Project | 18+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,157 ratings)
Course Price

View Course

Related Courses
All in One Data Science Bundle (360+ Courses, 50+ projects)Data Visualization Training (15 Courses, 5+ Projects)

Output:

PowerShell SubString 3

  • 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:

string 1

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:

PowerShell SubString 4

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:

PowerShell SubString 5

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:

PowerShell SubString 6

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:

 string 4

  • 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:

PowerShell SubString 7

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:

string 2

  • 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:

string 3

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 –

  1. PowerShell Escape Character
  2. PowerShell not like
  3. PowerShell Filter
  4. PowerShell Delete File

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Rename Folder
    • PowerShell String Replace
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Get-ADUser
    • PowerShell Start-Process
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV 
    • PowerShell Export CSV
  • Basics
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Versions
    • How To Install PowerShell
    • How to Use PowerShell?
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Modules
    • Variable in PowerShell
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell vs PowerShell ISE
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
  • cmdlet
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • PowerShell Out-File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Shell Scripting Course Learn More