0
0
PowerShellscripting~5 mins

String methods (.Split, .Replace, .Trim) in PowerShell

Choose your learning style9 modes available
Introduction

String methods help you change or break text easily. They make working with words simple and fast.

You want to break a sentence into words.
You need to change some words in a text.
You want to remove extra spaces from the start or end of a text.
You want to clean up user input before using it.
You want to split a list of items separated by commas.
Syntax
PowerShell
$string.Split('separator')
$string.Replace('old', 'new')
$string.Trim()

.Split() breaks a string into parts using a separator.

.Replace() changes old text to new text.

.Trim() removes spaces from start and end.

Examples
Splits the string into an array: apple, banana, orange.
PowerShell
'apple,banana,orange'.Split(',')
Changes 'world' to 'PowerShell' in the string.
PowerShell
'hello world'.Replace('world', 'PowerShell')
Removes spaces before and after 'hello'.
PowerShell
'  hello  '.Trim()
Sample Program

This script cleans spaces, splits the fruit list, replaces 'banana' with 'grape', and prints each fruit on its own line.

PowerShell
$text = '  apple, banana, orange  '

# Remove spaces at start and end
$cleanText = $text.Trim()

# Split the string into fruits
$fruits = $cleanText.Split(', ')

# Replace 'banana' with 'grape'
$fruits = $fruits | ForEach-Object { $_.Replace('banana', 'grape') }

# Show each fruit
foreach ($fruit in $fruits) {
    Write-Output $fruit
}
OutputSuccess
Important Notes

Use .Split() with the exact separator you expect, like ', ' for comma and space.

.Replace() does not change the original string; it returns a new one.

.Trim() only removes spaces at the start and end, not inside the text.

Summary

.Split() breaks text into parts using a separator.

.Replace() swaps old text with new text.

.Trim() cleans spaces from the start and end of text.