PSMonday #21: Monday, September 19, 2016

Topic: Get-Member Continued III (and Arrays)

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

At this point, we’ve only ever piped to the Get-Member cmdlet, but there’s times we might want to use the cmdlet differently. Before we continue, we need to understand arrays, and so we’re going to break off from Get-Member this week.

In our previous examples, we’ve typically only assigned a single value to a variable.

$a = 'dog'
$a

dog

Using an array allows us to assign multiple values to a single variable. Here’s how we do that, and how it appears when we return the variable’s newly assigned values.

$b = 'dog','cat','bird','frog'
$b

dog
cat
bird
frog

You may see arrays created using the array operator syntax, as well: @().

$b = @('dog','cat','bird','frog')

We can access each of the values in the array variable using an index. This is the position of a value within the array. Arrays are always zero-based, so the first value in the array is always at index 0.

$b[0]

dog

Now let’s return all four values. We’ll do them out of order, so you can see that the indexes really do, return the proper value in the array.

$b[3] # 4th value.
$b[0] # 1st value.
$b[2] # 3rd value.
$b[1] # 2nd value.

frog
dog
bird
cat

We’ve learned that the array index 0 and then higher, each represent the next value in the array. We can also move backwards through an array, using negative indexes. Here’s both.

$b[0]
$b[1]
$b[2]
$b[3]
'--------'
$b[-1]
$b[-2]
$b[-3]
$b[-4]

dog
cat
bird
frog
--------
frog
bird
cat
dog

This means that index [-1] is always the last value in an array, just like index [0] will always be the first. Knowing this may come in handy one day; it was for me. Next Monday, we’ll actually get back to Get-Member, now that we have some basic understanding of arrays, if you didn’t have them already.

Leave a Reply

Your email address will not be published. Required fields are marked *