Text Splitting

by Sep 29, 2014

All PowerShell Versions

With the –split operator, you can split text at given locations. The operator expects a regular expression, so if you just want to split using plain text expressions, you need to escape your split text.

Here is an example that splits a path at the backslash:

$originalText = 'c:\windows\test\file.txt'
$splitText = [RegEx]::Escape('\')

$originalText -split $splitText 

The result looks like this and is an array:

PS> $originalText -split $splitText
c:
windows
test
file.txt 

Store it in a variable to access the individual array elements:

PS> $parts = $originalText -split $splitText

PS> $parts[0]
c:

PS> $parts[-1]
file.txt

Twitter This Tip! ReTweet this Tip!