Sunday, February 20, 2011

Using Windows PowerShell as an IT Pro – Part 13

Using Windows PowerShell as an IT Pro – Part 13

In my last post I looked at some basic variable types. Now I will examine arrays.
An array is a data structure for storing a collection of data elements of the same type. Basically this means that you can have a single variable that stores multiple values.
Assign multiple values to a variable to create and initialize an array. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator (=).
For example, to create an array named $a that contains the seven numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type:
$a = 20,4,11,3,1,9,60

When no data type is specified, Windows PowerShell creates each array as an object array (type: object[]). You can create a strongly typed array, that is, an array that can contain only values of a particular type, the same way you create a strongly typed variable. You specify a type, such as string[], long[], or int32[]. Precede the variable name with an array type enclosed in brackets to cast an array.
[int32[]]$ia = 1500,2230,3350,4000

Simply type the array name to display all the elements in the array. For example:
$ia

You can refer to the elements in an array by using an index, beginning at position 0. Enclose the index number in brackets. For example, to display the third element in the $a array, type:
$ia[2]

You can create arrays that are cast to any supported type in the Microsoft .NET Framework. For example, the objects that Get-Process retrieves to represent processes are of the System.Diagnostics.Process type. Enter the following command to create a strongly typed array of process objects.
[Diagnostics.Process[]]$gp = Get-Process

Then, display the contents of $gp to see a list of running processes.
$gp

In my next post we will review operators and expressions.

No comments:

Post a Comment