An array
is a container that is used for storing a collection of data elements.
An array in Windows PowerShell can contain objects of all types
supported by .NET. All arrays are origin zero, meaning that the first
element in an array is always at index 0, the second element is at
index 1, and so on. Many cmdlets in Windows PowerShell return output in
the form of an array.
Here is an example of creating a simple array containing numeric values:
PS > $array = 1,2,3
PS > $array
1
2
3
You can also create an array using the array subexpression operator @, as shown here:
You can access specific elements in arrays. To retrieve the first element, type the following:
Notice
how we use the value 0 to retrieve the first element, since the
indexing of array elements in Windows PowerShell starts with zero. If
we used 1, the second element would be returned.
You can change an element in an array by assigning it a new value, as in this example:
PS > $array[1] = "Two"
PS > $array
1
Two
3
Use the += operator to add an element to an array.
PS > $array += "Four"
PS > $array
1
Two
3
Four
You can also count the number of elements in an array by using the Count property.
Note
The Count property used in this example is actually an alias for the System.Array Length
property. It is available through the types.ps1.xml file, which is a
built-in XML file that adds several elements to the .NET Framework
types in Windows PowerShell.
When cmdlets return more than one result, Windows
PowerShell automatically wraps the result into an array. In the
following example, we store the output of the Get-SPWebTemplate cmdlet in a variable and use the Count property to check how many elements the array contains.
PS > $SPWebTemplate = Get-SPWebTemplate
PS > $SPWebTemplate.Count
50
Again, if we want to retrieve the first element, we can simply type the following:
PS > $SPWebTemplate[0]
Name Title LocaleId Custom
---- ----- -------- ------
GLOBAL#0 Global template 1033 False
You can also use ranges when retrieving elements in an array.
PS > $SPWebTemplate[0..2]
Name Title LocaleId Custom
---- ----- -------- ------
GLOBAL#0 Global template 1033 False
STS#0 Team Site 1033 False
STS#1 Blank Site 1033 False
It is even possible to use negative numbers when working with arrays. To retrieve the last element in the array, use -1.
PS > $SPWebTemplate[-1]
Name Title LocaleId Custom
---- ----- -------- ------
visprus#0 Visio Process Repository 1033 False