EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell SubString
Secondary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • 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 Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • 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 Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • 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 do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • 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

PowerShell SubString

By Priya PedamkarPriya Pedamkar

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:

Before looking at the substring(), let’s see the list of operations that are available for any string object.

Input:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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)

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

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,354 ratings)

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
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • 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

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

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

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more