Powershell provides the -split
option and Split()
method for splitting string variables and values. Both -split option and Split() method have valid usage. They provide the same options. The split operation can be executed to split with specified characters, split with multiple characters, split with multiple separators, split with space characters, split a CSV file, MAC, and IP address.
Split Option and Method Syntax
The split option is used with the string values where the Split() method can be used with string values and string variables. The split result is returned as an array. If the split result is redirected to the terminal every item in the resulting array is printed line by line.
STRING_VALUE -split CHAR
STRING_VARIABLE.Split(OPTIONS)
- STRING_VALUE is a value which is string like “abc”.
- STRING_VARIABLE is a variable which type is string like $demo=”abc”.
- CHAR is the split character or multiple chraracters to split specified string value.
- OPTIONS is split character or multiple characters to split specified string variable content.
Split with Specified Character
The most popular and basic usage of the split is providing a single character to split the provided string. The character is provided as -split option value or parameter to the Split() method. In the following example, we split the string value “I,like,to,play,football” which is also used as a string variable.
"I,like,to,play,football." -split ","
$str = "I,like,to,play,football."
$str.Split(",")
I like to play football. I like to play football.
The split operations result is like above. All commas are removed and characters between commas are returned as a string array.
Split with Multiple Characters
The split operation can be executed with multiple characters as a separator. In the following example, we use “-,” characters as separators.
"I-,like-,to-,play-,football." -split "-,"
$str = "I-,like-,to-,play-,football."
$str.Split("-,")
I like to play football. I like to play football.
Split with Space Character
One of the most popular usages for the split operation is using the space characters as separators. The space is used to separate the words in a sentence. In the following example, we use the space characters as separator.
"I like to play football." -split " "
$str = "I like to play football."
$str.Split(" ")
I like to play football. I like to play football.
Split MAC Address
MAC address is used to address an ethernet or wireless network interface. The MAC Address has two popular expression formats where the address values are separated with the “-” or “:”. The Split method can be used to split a MAC address into elements.
$MacAddress ="23-21-45-78-9A-BC"
$MacAddress.Split("-")
$MacAddress ="23:21:45:78:9A:BC"
$MacAddress.Split(":")
![](/wp-content/uploads/2021/08/image-38.png)