Problem
You want to create an array or list of items.
Solution
To create an array that holds a given set of items, separate those items with commas:
PS >$myArray = 1,2,"Hello World" PS >$myArray 1 2 Hello World
To create an array of a specific size, use the NewObject cmdlet:
PS >$myArray = NewObject string[] 10 PS >$myArray[5] = "Hello" PS >$myArray[5] Hello
To store the output of a command that generates a list, use variable assignment:
PS >$myArray = GetProcess PS >$myArray
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
274 6 1316 3908 33 3164 alg 983 7 3636 7472 30 688 csrss 69 4 924 3332 30 0.69 2232 ctfmon 180 5 2220 6116 37 2816 dllhost (...)
To create an array that you plan to modify frequently, use an ArrayList, as shown by Example 111.
Example 111. Using an ArrayList to manage a dynamic collection of items
PS >$myArray = NewObject System.Collections.ArrayList PS >[void] $myArray.Add("Hello") PS >[void] $myArray.AddRange( ("World","How","Are","You") ) PS >$myArray Hello World How Are You PS >$myArray.RemoveAt(1) PS >$myArray Hello How Are You
Discussion
Aside from the primitive data types (such as strings, integers, and decimals), lists of items are a common concept in the scripts and commands that you write. Most commands generate lists of data: the GetContent cmdlet generates a list of strings in a file, the GetProcess cmdlet generates a list of processes running on the system, and the GetCommand cmdlet generates a list of commands, just to name a few.
The solution shows how to store the output of a command that generates a list. If a command outputs only one item (such as a single line from a file, a single process, or a single command), then that output is
no longer a list. If you want to treat that output as a list even when it is not, use the list evaluation syntax ( @() ) to force PowerShell to interpret it as an array:
$myArray = @(GetProcess Explorer)