Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend an element to an array in Powershell?

Tags:

powershell

The Powershell code:

$list += "aa" 

appends the element "aa" to the list $list. Is there a way to prepend an element? This is my solution, but there must be a way to do this in a single line.

$tmp = ,"aa"; $tmp += $list $list = $tmp 
like image 276
Nestor Avatar asked Feb 04 '10 17:02

Nestor


People also ask

How do you append to an array in PowerShell?

To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator. For example, you have an existing array as given below. To add value “Hello” to the array, we will use += sign.

What is prepend array?

Inserts an array element at the beginning of an array and shifts the positions of the existing elements to make room.

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

How do I get the first element of an array in PowerShell?

Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].


2 Answers

In your example above, you should just be able to do:

$list = ,"aa" + $list 

That will simply prepend "aa" to the list and make it the 0th element. Verify by getting $list[0].

like image 196
nithins Avatar answered Sep 24 '22 15:09

nithins


Using += and + on arrays in PowerShell is making a copy of the array every time you use it. That is fine unless the list/array is really large. In that case, consider using a generic list:

C:\> $list = new-object 'System.Collections.Generic.List[string]' C:\> $list.Add('a') C:\> $list.Add('b') C:\> $list.Insert(0,'aa') C:\> $list aa a b 

Note that in this scenario you need to use the Add/Insert methods. If you fall back to using +=, it will copy the generic list back to an object[].

like image 23
Keith Hill Avatar answered Sep 21 '22 15:09

Keith Hill