PowerShell: How to Split String into Separate Variables


You can use the following methods to split a string into separate variables in PowerShell:

Method 1: Split Each Word in String into Variable

$one, $two, $three = $my_string.split(' ')

This particular example will split the string variable named $my_string based on where the spaces occur in the string and then assign each individual word to separate variables named $one, $two and $three.

Method 2: Split Specific Number of Words in String into Variable

$one, $two = $my_string.split(' ')[0, 1]

This particular example will split the string variable named $my_string based on where the spaces occur in the string and then assign the first two individual words to separate variables named $one and $two.

The following examples show how to use each method in practice.

Example 1: Split Each Word in String into Variable

We can use the following syntax to define a string variable in PowerShell and then assign each word in the string to a separate variable:

$basketball_info = "Mavs Starting Guard"

$team, $rank, $position = $basketball_info.split(' ') 

The following screenshot shows how to use this syntax in practice:

PowerShell split string into variables

We can see that the string has been split into three variables named $team, $rank and $position.

From the output we can see the values for these variables:

  • The $team variable contains “Mavs”
  • The $rank variable contains “Starting”
  • The $position variable contains “Guard”

Example 2: Split Specific Number of Words in String into Variable

We can use the following syntax to define a string variable in PowerShell and then assign the first two words in the string to separate variables:

$basketball_info = "Mavs Starting Guard"

$team, $rank = $basketball_info.split(' ')[0, 1]

The following screenshot shows how to use this syntax in practice:

We can see that the first two words of the string have been split into two variables named $team and  $rank.

From the output we can see the values for these variables:

  • The $team variable contains “Mavs”
  • The $rank variable contains “Starting”

Note: In both of these examples we split the string based on where the spaces occur in the string, but you can use any separator you would like within split() to instead split the string on a different character.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Text in String
PowerShell: How to Get String Length of Variable
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply