PowerShell Split a String On First Occurrence of Substring/Character PowerShell Split a String On First Occurrence of Substring/Character powershell powershell

PowerShell Split a String On First Occurrence of Substring/Character


PowerShell's -split operator supports specifying the maximum number of sub-strings to return, i.e. how many sub-strings to return. After the pattern to split on, give the number of strings you want back:

$header,$content = "Header text,Text 1,Text 2,Text 3,Text 4," -split ',',2


Try something like :

$Content=$String.Split([string[]]"$Header,", [StringSplitOptions]"None")[1]

As you split according to a String, you are using a different signature of the function split.

The basic use needs only 1 argument, a separator character (more info about it can be found here, for instance). However, to use strings, the signature is the following :

System.String[] Split(String[] separator, StringSplitOptions options)

This is why you have to cast your string as an array of string. We use the None option in this case, but you can find the other options available in the split documentation.

Finally, as the value of $Heasder, is at the beggining of your $String, you need to catch the 2nd member of the resulting array.


method of Aaron is the best, but i propose my solution

$array="Header text,Text 1,Text 2,Text 3,Text 4," -split ','$array[0],($array[1..($array.Length -1)] -join ",")