Sunday, May 13, 2012

Hip-hip, Array

PowerShell variables all start with a dollar sign ($) so they are easily identifiable and possibly to indicate they have value.  You can assign a static value:
Or you can assign the value from the pipeline:
 

Many times the results of a pipeline will be an array.  Array?
No, not a "Ray".

An array is a sequential collection of objects (sometimes referred to as elements).  Each object in the collection can be referenced by an index number of its place in the sequence.  Enclose the index number in square brackets ([]) to retrieve that particular element.
Note that counting elements starts at 0.  And you can use the Length attribute to determine how many elements are in the array.

You can assign static values by assigning a comma separated list after the equal sign.  You can also provide a range of numeric values surrounding an ellipsis (..):

You can add an element to the end of an array using the plus sign (+):
Combing the plus and equals sign implies that we are adding the value to the variable on the left of the equation:
Something useful to note is that in Powershell the array doesn't have to include elements of the same type:

Usually we will use an array that is returned from the pipeline:
Get-Process returns all of the running processes.  I assign that output to the array $Procs.  I'm showing just the first 6 to save screen real estate and showcase another use of the ellipsis.

What if I want to do something with each element of the array?  I could create a for loop using the c-styled structure.  for ($i=0;$i -lt $procs.length;$i++) {#commands}.  But that is an old-school way of looping through an array.

Instead use the ForEach-Object cmdlet which loops through the array retrieving one element at a time.  You can pipe the variable into the foreach and use the automatic variable $_ to process the array elements:

The automatic variable $_ is handy if you are processing something along the pipeline.  But if you need to run multiple commands against the elements or do more complex processing it is often easier to assign a variable to each element:
In this example I get the running processes.  I use the ForEach-Object cmdlet to loop through the array and find processes that consume a lot of memory and CPU.  I then exact my revenge on these processes through petty name calling.

If you will be working with PowerShell you need to get used to working with arrays.  Check out some of the resource links on the sidebar for more useful tips on working with them.

Commentors: Did I miss any good Ray's in the links?

No comments:

Post a Comment