[PowerShell Tip] – Assign array elements to separate variables in single line of code


In this post, we’ll see how we can assign array elements to separate variables in a single line of code

Consider a sample array

$TestArray = @("FirstElement", "SecondElement")

Now, to get the value of the elements into separate variables, we just need to declare the variables separated by a comma and at the end, assign the array to it as shown below.

$FirstValue, $SecondValue = $TestArray

When you print the $FirstValue and $SecondValue variables, you will see that they hold the values of the corresponding array element.

One use-case where we could use this is when we have a string that we need to split and we need to use let’s say all parts of the string.

Let’s say for example we have a string as given below

Amogh Natu;28;M;Hyderabad;India

We could read the whole string first and then split it using the character “;” and assign the resultant array to 5 variables namely, “FullName”, “Age”, “Sex”, “City”, “Country” and use these variables later in the code as needed.

Although, one point to remember here is that this is feasible and advisable to use when we know the array is going to have limited number of elements. It doesn’t make sense to use this technique if we know that the array has a lot of elements or is dynamic.

Hope this helps!

Leave a Reply
