Wednesday, March 16, 2016

PowerShell v3 in a Year Day 6 about Arrays

,
Arrays are one of the most basic data structures used in PowerShell used for storing elements. More specifically, arrays are reference type objects used to store collections of elements of the same type. PowerShell supports both value types (int, string, bool, byte, etc) and instance types (primarily classes and other .NET objects).

Creating and initializing array

Two of the easiest ways are to:
  1. Create an empty array
  2. Create an array by assigning multiple members to a variable
An empty array, that is, one with no members, can be created with a simple assignment as shown below:
  • $array = @()
An array with members can be created multiple ways:
  • $array = , 1
  • $array = 1,2,3
  • $array = @(1,2,3)
  • $array = 1..3 (this syntax is known as a range operator)
  • 1..3 | % { $array += $_ }
Validating objects are Arrays

Testing to see if an object is an array can be done a few different ways as well:
  • $array.GetType()
  • $array -is [System.Array]
  • $array | Get-Member
Exploring Array Members

There are a variety of properties to gather of the basic Array collection object. You can explore the methods and properties on the System.Array object in the MSDN documentation: Array Class. Many of the most basic properties can be accessed by using the property derferencing (dot) notation:
  • $array.count
  • $array.length
Working with Specific Array Items via Indexes

If I want to find out about specific members of the collection I can use the indexers. Indexes are a special notation where you indicate the position in the collection of the item you want to reference. Place this number inside a pair of square brackets. One of the simple, but, often confusing things about array indexes is that they start on 0 instead of 1 in PowerShell (and many programming languages). So, if we have an array with 3 members, the first member can be referenced with the index $array[0] and the last, that is the third item, can be referenced with the index $array[2]. When I use this syntax I will get the value of the item at that index position. So, here is a series of examples:
  • $array  = 1,2,3
  • $array[0] returns 1
  • $array[1] returns 2
  • $array[2] returns 3
This is the syntax used to access the getter for the index value. To access the setter, that is, to set the value of an item at a specific index position to a new or different value, simply place the array object name on the left hand side of an equal side and place the new value on the right hand side. like so: $array[0] = 4. Now, when I iterate over $array I get:
$array
4
2
By doing so, I have changed the value of  $array[0]  from 1 to 4. 

Working with Arrays and Constrained (Typed) Collections

One of the nice things about arrays is they are polymorphic. This is a CS way of saying, you can change the data type of the elements contained in the array with a simple assignment. So, taking our previous example, $array[0] = 4, we can demonstrate how to set not only a new value, but, a new value type (in this case as string) by using the same = operator with a string value instead of an integer: $array[0] = a string. Iterating over  $array, we now get 
astring
2
It is possible to create strongly-typed (or constrained) arrays, but, in many cases, that is unnecessary. To do so, simply declare the type you want to assign to the array:
[string[]]$array =1,2,
Interestingly, if you try to sneak in an integer under the radar, PowerShell will ignore the type of the incorrect value and cast it as a the type indicated in the type declaration. For example,
PS> [string[]]$array =1,2,3
PS> $array
1
2
3
PS> $array| % { $_.GetType() }

IsPublicIsSerial Name                                     BaseType
---------------- ----                                     --------
True     True     String                                   System.Object
True     True     String                                   System.Object
True     True     String                                   System.Object
If no type is specified PowerShell simply assumes an array of [Object[]]. To be sure you know what you are in fact working with, just use the $array.GetType() method against the array. In this case, it outputs,
IsPublicIsSerial Name                                     BaseType           
---------------- ----                                     --------           
True     True     Object[]                                 System.Array 
It is good to be aware that you can type an array to any viable .NET object. So, if you are working with an array of Process objects, use this syntax:  [Diagnostics.Process[]]$zz= Get-Process

Storing Output in Arrays

Equally important to be aware of is the fact that you can store the output of cmdlets, functions or statements in arrays. If your output returns a single object, the resulting object is a singleton, and, not an array. To force it to be array, regardless of whether the result is a singleton or not, wrap your function, cmdlet or statement in the array subexpression operation @(). For example, if you run this command
$LocalProcesses= @(get-processco*)
and it only returns one object, $LocalProcesses will still be an array because you wrapped Get-Process in @().

Reading Through Arrays

Reading arrays is a basic operation. To see all members of an array, simply type the variable name: $array.  This will list all items in the collection. Referring to specific elements can be done, as noted earlier, by referencing the specific index of the item. For instance, if you wanted to see the 2nd item in our $array collection, type $array[1]. Recall, arrays are zero-based collections which simply means the first members index value is 0, not 1. 

A good syntactic tool to know about is the use of negative index values. When an index value is used it indicates the position relative to the last item in the collection. So, to reference the last item in a collection you could use two different approaches:
  1. $array[$array.Count -1]
  2. $array[-1
Both of these statements return the value 3, which is the value of the last item in the array.

Below are a variety of tricks you can use to refer to all sorts of specific values:
  • $array= 1..7 sets a new array with values 1 through 7
  • $array[-3..-1] returns 5, 6 and 7
  • $array[0..-2] returns 1, 7 and 6
  • $array[1..3] returns 2, 3 and 4
  • $array[0,2+4..6] returns 1, 3, 5, 6 and 7
  • $array[2..($array.length-1)] returns 2, 3 and 4
  • $array[-1..-7] returns 7, 6, 5, 4, 3, 2 and 1
Arrays and Looping

Looping constructs permeate PowerShell logic and work extensively with arrays. For example, array indexes are useful when working with for loops, such as:
for($i = 0; $i -le ($a.length - 1); $i += 2) {$a[$i]}
Or, if you need to use array indexes with arrays and while loops you can use something like this
$i=0
while($i -lt 4) {$a[$i]; $i++}
If you want to get details about an array, use the Get-Member cmdlet with the -InputObject parameter. In v2 of PowerShell, you could simply pipe an array to Get-Member and it would return information about the array. In v3, piping an array to Get-Member rather returns information about the items in the collection, not,

0 comments to “PowerShell v3 in a Year Day 6 about Arrays”

Post a Comment

 

Computer Info Copyright © 2016 -- Powered by Blogger