Coding Ref

How to trim text in PowerShell

How to trim text in PowerShell

To trim text in PowerShell, you can use the Trim() method. This method allows you to remove leading and trailing white space from a string.

Examples

Example 1

Here is an example of how to use the Trim() method to trim text in PowerShell:

$myString = "  This is a string with leading and trailing white space.  "

# Trim the leading and trailing white space from the string
$trimmedString = $myString.Trim()

# Output the trimmed string
Write-Host $trimmedString

In this example, the Trim() method is called on the $myString variable to remove the leading and trailing white space.

The resulting trimmed string is then stored in the $trimmedString variable, and is output to the screen.

You can also use the TrimStart() and TrimEnd() methods to trim only the leading or trailing white space from a string.

Example 2

For example, the following code uses the TrimStart() method to trim only the leading white space from the string:

$myString = "  This is a string with leading and trailing white space.  "

# Trim only the leading white space from the string
$trimmedString = $myString.TrimStart()

# Output the trimmed string
Write-Host $trimmedString

In this example, the TrimStart() method is called on the $myString variable to remove only the leading white space. The resulting trimmed string is then output to the screen.

Conclusion

To trim text in PowerShell, you can use the Trim() method. This method allows you to remove leading and trailing white space from a string.

You'll also like

Related tutorials curated for you

    How to get the host or computer name in PowerShell

    What is read-host in PowerShell?

    What is WhatIf in PowerShell?

    How to move items in PowerShell

    Boolean literals in PowerShell

    Do Until in PowerShell

    How to use ErrorAction in PowerShell

    How to sort in PowerShell

    What is a Scriptblock in PowerShell?

    What is PowerShell logging?

    How to check for equality in PowerShell

    How to sort and filter data in PowerShell