PowerShell: How to Split String to Get First and Last Element


Often you may want to split a string based on a specific delimiter in PowerShell and then retrieve the first and last elements that result from the split.

You can use the following syntax to do so:

$first_val = $my_string.Split("-")[0]
$last_val = $my_string.Split("-")[-1]

This particular example splits the string stored in the variable named $my_string and then saves the first element in a variable named $first_val and saves the last element in a variable named $last_val.

Note that we use the Split() method to specify that the original string should be split using a dash as a delimiter.

We then use the bracket notation [0] to retrieve the first value from the split and [-1] to retrieve the last value from the split.

Note that you could also use the following syntax to get the first and last elements if you’d like even shorter syntax:

$first_val, $last_val = $my_string.Split("-")[0, -1]

The following example shows how to use this syntax in practice.

Example: Split String to Get First and Last Element in PowerShell

Suppose we create a string variable named $my_string in PowerShell that contains various information about some basketball player:

  • Dallas-Mavericks-Starting-Forward

We can use the following syntax to split this string based on where the dashes occur and then get the first and last elements:

$my_string = "Dallas-Mavericks-Starting-Forward"

$first_val = $my_string.Split("-")[0]
$last_val = $my_string.Split("-")[-1]

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

PowerShell split string get first and last element

Notice that $first_val contains the first element from the string with a value of Dallas.

We can also see that $last_val contains the last element from the string with a value of Forward.

Note that we could also use the following one-line approach to get the first and last elements:

$my_string = "Dallas-Mavericks-Starting-Forward"

$first_val, $last_val = $my_string.Split("-")[0, -1]

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

Once again, the variable $first_val contains the value Dallas and the variable $last_val contains the value Forward.

Feel free to use whichever method you prefer.

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