0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Split String by Delimiter

Use the -split operator in PowerShell like this: $parts = $string -split ',' to split a string by a comma delimiter.
📋

Examples

Inputapple,banana,orange
Output["apple", "banana", "orange"]
Inputone|two|three|four
Output["one", "two", "three", "four"]
Inputnospace
Output["nospace"]
🧠

How to Think About It

To split a string by a delimiter in PowerShell, think of the string as a sentence and the delimiter as the space or comma that separates words. You use the -split operator with the delimiter to break the string into parts, which PowerShell returns as an array.
📐

Algorithm

1
Get the input string.
2
Choose the delimiter character or string to split by.
3
Use the split operator to divide the string at each delimiter occurrence.
4
Store the resulting parts in an array.
5
Return or output the array of split parts.
💻

Code

powershell
$string = "apple,banana,orange"
$delimiter = ","
$parts = $string -split $delimiter
Write-Output $parts
Output
apple banana orange
🔍

Dry Run

Let's trace splitting 'apple,banana,orange' by ',' through the code

1

Set string and delimiter

$string = 'apple,banana,orange', $delimiter = ','

2

Split string

$parts = $string -split $delimiter results in ['apple', 'banana', 'orange']

3

Output result

Write-Output prints each element on a new line

IndexValue
0apple
1banana
2orange
💡

Why This Works

Step 1: Using -split operator

The -split operator divides a string into parts wherever the delimiter appears.

Step 2: Result is an array

The output is an array of substrings, each between delimiters.

Step 3: Output displays each part

Using Write-Output prints each array element on its own line.

🔄

Alternative Approaches

Using .Split() method
powershell
$string = "apple,banana,orange"
$parts = $string.Split(',')
Write-Output $parts
This method is from .NET and works similarly but is a method call instead of an operator.
Using regex with -split
powershell
$string = "apple;banana|orange"
$parts = $string -split '[;|]'
Write-Output $parts
You can split by multiple delimiters using a regex pattern inside -split.

Complexity: O(n) time, O(n) space

Time Complexity

Splitting scans the entire string once, so time grows linearly with string length.

Space Complexity

The output array stores all parts, so space grows with the number of splits.

Which Approach is Fastest?

Both -split and .Split() have similar performance; regex splitting is slower due to pattern matching.

ApproachTimeSpaceBest For
-split operatorO(n)O(n)Simple delimiter splitting
.Split() methodO(n)O(n)Using .NET string methods
Regex with -splitO(n) but slowerO(n)Multiple delimiters or patterns
💡
Use -split for simple delimiter splitting and .Split() for .NET string methods.
⚠️
Forgetting that -split returns an array, so treating it like a single string causes errors.