Splitting a string into separate variables Splitting a string into separate variables powershell powershell

Splitting a string into separate variables


Like this?

$string = 'FirstPart SecondPart'$a,$b = $string.split(' ')$a$b


An array is created with the -split operator. Like so,

$myString="Four score and seven years ago"$arr = $myString -split ' '$arr # Print outputFourscoreandsevenyearsago

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

$arr[2] # 3rd elementand$arr[4] # 5th elementyears


It is important to note the following difference between the two techniques:

$Str="This is the<BR />source string<BR />ALL RIGHT"$Str.Split("<BR />")Thisisthe(multiple blank lines)sourcestring(multiple blank lines)ALLIGHT$Str -Split("<BR />")This is thesource stringALL RIGHT 

From this you can see that the string.split() method:

  • performs a case sensitive split (note that "ALL RIGHT" his split on the "R" but "broken" is not split on the "r")
  • treats the string as a list of possible characters to split on

While the -split operator:

  • performs a case-insensitive comparison
  • only splits on the whole string