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 Trim
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

PowerShell Trim

PowerShell Trim

Introduction to PowerShell Trim

PowerShell Trim() methods (Trim(), TrimStart() and TrimEnd()) are used to remove the leading and trailing white spaces and the unwanted characters from the string or the raw data like CSV file, XML file, or a Text file that can be converted to the string and returns the new string. These methods are part of the System.String .Net Class, and once these methods are applied, it produces the new string instead of manipulating the current string.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  • Trim(): Trims (Removes) all the leading and trailing white space characters from the current string object.
  • Trim(Char[]): It removes all the leading and trailing characters from the current string object.
  • TrimeStart: It removes all occurrences of a character from the beginning of the current string object.
  • TrimEnd: It removes all occurrences of a character from the end of the current string object.

How does Trim Function work in PowerShell?

Trim() methods are System.String .NET class methods and used to eliminate the leading and/or trailing characters, including whitespace from the string. They are only available in the string class.

Code:

$str = " This is a PowerShell String "
$str | gm

Output:

PowerShell Trim 1

In the above output, all Trim() methods return a string that is the new string after the operation, and that is why we need to store it to the new variable if it requires further operation on it. Other datatypes don’t support Trim() methods.

Examples of PowerShell Trim

Given below are the examples of PowerShell Trim:

Example #1 – Trim() method.

This function will remove the leading and trailing whitespaces from the string object, as shown below.

Code:

$str = " This is a PowerShell String "
$str.Trim()

Output:

PowerShell Trim 2

You might have noticed that it generates a new string. We can save this string to the new variable for later use.

Code:

$str = " This is a PowerShell String "
$str1 = $str.Trim()
$str1

Output:

PowerShell Trim 3

You can also directly pass a string instead of a variable and operate on it.

Code:

(" This is a PowerShell String ").Trim()

Output:

PowerShell Trim 4

It is just removing spaces, so we will check the output length before and after trimming whitespaces because trimmed whitespaces may not be visible in the output.

Code:

$str = " This is a PowerShell String "
$str.Length
29

After removing whitespace.

Code:

$str1 = $str.Trim()
$str1.Length
27

Example #2 – Trim(Char) method to trim specific character.

Suppose we have the below string to trim its starting and ending character.

Code:

$str = "aThis is a PowerShell String"
$str.Trim('a')

Output:

PowerShell Trim 5

Here we have provided a character ‘a’ to trim, and in the string, ‘a’ is at the start of the string but not at the end of the script. So it removes only the start character. If the ‘a’ is at both ends, then the leading and trailing character ‘a’ will be removed.

Code:

$str = "aThis is a PowerShell Stringa"
$str.Trim('a')

Output:

PowerShell Trim 6

Below is also the same operation.

Code:

$str.Trim("a"," ")

Output:

PowerShell Trim 7

The question is, what if we have the leading or trailing space and if we provide the first character to remove.

Code:

$str = " aThis is a PowerShell String"
$str.Trim('a')

Output:

PowerShell Trim 8

The command won’t perform any action on the string because its leading character is whitespace.

Please note trimming the specific character is a case sensitive operation.

Code:

$str = "aThis is string trimming"
$str.Trim('A')

Output:

PowerShell Trim 9

Code:

$str.Trim('G')

Output:

PowerShell Trim 10

Example #3 – Trim (Unicode) method to trim specific character.

The good thing about PowerShell is that we can also pass the Unicode character and then type conversion to character data to trim leading and trailing characters.

Code:

$str = "aThis is string trimming"
$str.Trim([char]0x0061)

Output:

Unicode

You can find the list of Unicode characters in the below link.

https://en.wikipedia.org/wiki/List_of_Unicode_characters.

The above example is similar to.

Code:

$str = "aThis is string trimming"
$str.Trim([char]0x0061,[char]0x0020)

Output:

PowerShell Trim 12

Here 0x0061 represents ‘a’ and 0x0020 represents whitespace.

Example #4 – Trim (Char[]) method to remove leading and trailing space.

In the above examples, we have used a single character that was removed from the start or the end of the string if it was matched. If we provide multiple characters, it will remove them from the leading and trailing characters. An explanation can be understood with the examples below.

Code:

("hello world").Trim('hd')

Output:

remove leading and trailing space

We have provided two characters, ‘hd’, and it will check both the characters at the start and end of the string, and if matched, it will remove them.

Code:

("dhello world").Trim('hd')

Output:

PowerShell Trim 14

From the above example, we can see that the character sequence doesn’t matter.

You can also remove the entire word using this method.

Code:

$str = "PowerShell hello PowerShell"
$str.Trim('PowerShell')

Output:

remove the entire word

Example #5 – TrimStart(Char) method.

In the Trim() method, we can delete leading and trailing characters while TrimStart() delete only leading character(s), as shown in the example below.

Code:

$str = "PowerShell helloP"
$str.TrimStart('P')

Output:

PowerShell Trim 16

If no character is specified inside, it will consider whitespace as a character and remove eliminate the whitespace at the beginning.

Code:

$str = " Hello World "
$str.TrimStart()

Output:

PowerShell Trim 17

In this example, trailing whitespace is note removed; we can check it by counting the number of words.

PowerShell Trim 18

Example #6 – TrimStart(Char[]) method.

We can also use the multiple leading characters to remove from the string.

Code:

$str = "PowerShell hello PowerShell"
$str.TrimStart("PowerShell")

Output:

(Char[]) method

Note: TrimStart() operation is also case sensitive, and we can use Unicode characters by converting them into character datatype for this operation.

Example #7 – TrimEnd() method.

We can use TrimEnd() method to remove trailing characters.

If we don’t specify anything, it will remove the ending whitespace but not the trailing whitespace.

Code:

$str = " Hello World "
$str.TrimEnd()

Output:

PowerShell Trim 20

Once we specify any character inside this method, it will remove the trailing character from the string.

Code:

PS C:\> $str = "dHello World"
PS C:\> $str.TrimEnd('d')

Output:

specify any character

If there are multiple same characters specified at the end, it will remove all trailing same characters.

Code:

$str = "dHello Wordd"
$str.TrimEnd('d')

Output:

remove all trailing same characters

We can also eliminate multiple trailing characters.

Code:

$str = "Hello PowerShell Hello"
$str.TrimEnd("Hello")

Output:

eliminate multiple trailing characters

Note: This operation is case-sensitive, and you can also use Unicode characters as shown in the earlier example to trim the string.

Conclusion

Trim functions are very helpful for the string operations, especially when we are working with the text file or the CSV file and we need to remove some entries from the string.

Recommended Articles

This is a guide to PowerShell Trim. Here we discuss the introduction, how to trim function works in PowerShell? and examples. You may also have a look at the following articles to learn more –

  1. PowerShell Sleep
  2. PowerShell SubString
  3. PowerShell not like
  4. Else If in PowerShell
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
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

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

EDUCBA

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

Let’s Get Started

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
EDUCBA

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

Forgot Password?

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