Powershell

Splitting a String into Separate Variables

A string is a data type in PowerShell, a combination of letters and characters used to define meaningful text. It can be specified within single or double quotes and has a “System.String” object type. More specifically, a PowerShell string can be split into variables using the built-in “Split()” method or the “-Split” operator.

This tutorial overview is a detailed guide to rectify the stated problem.

How to Split/Divide a String into Separate/Multiple Variables in PowerShell?

These methods can be applied to resolve the mentioned query:

Method 1: Split a String into Separate Variables in PowerShell “Split()” Method

The “Split()” is a built-in function or method in PowerShell that is dedicated to split strings into variables. For instance, we have added an example to exemplify the procedure to split a string into multiple variables.

Example

This example will demonstrate the method to split a string into multiple variables using the “Split()” method or function:

> $string = "Dog is beautiful"

> $a, $b, $c = $string.Split()

> $a

> $b

> $c

According to the given code:

  • First, we have created a string and assigned it to a variable “$string”.
  • After that, we concatenate the string with the “Split()” method and assign three variables separated by commas. Doing so will split the string and assign it to the three variables.
  • Now, call the three variables for verification:

The output confirms that the string has been successfully converted into variables.

Method 2: Split/Divide a String into Separate/Multiple Variables in PowerShell Using “-Split” Operator

The “-Split” operator or flag can also be utilized solely for splitting the string into multiple variables.

Example

In this example, we will use the “-Split” operator to split the string and store the value into multiple variables:

> $string = "Dog is beautiful"

> $a, $b, $c = $string -Split " "

> $a

> $b

> $c

In this example code, we added the “-Split” operator along with the string variable and assigned it to the three variables separated by commas. Then, call those variables one by one to check whether the string was split into separate variables or not:

That was all about splitting a string into separate variables.

Conclusion

A string in PowerShell can be split into separated variables using two methods. These methods include the “Split()” function and the “-Split” operator. Both of the methods are specially designed to split a string. This write-up has presented a thorough guide to splitting a string into multiple variables.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.