T-SQL Tuesday #127 – Non SQL Tips and Tricks, Referencing Multiple PowerShell Array Elements

This month’s T-SQL Tuesday invitation is from Ken Fisher and he’s asking about non-SQL tips and tricks.

This had me thinking for a bit and then something popped into my head, an accidental discovery that I made the other day. I apologise if this is common knowledge among the PoSH guys but it was a new one on me (and I’m happy to hold my hand up to being a bit of a PowerShell noob).

It turns out that we can reference multiple entities in an array.

What do I mean, lets take a look. First we’re going to create a simple array of 90s BritPop bands.

$array = 'Pulp','Blur','Oasis','Supergrass','The Verve'

If we want to interact with an element in that array, we need to reference it’s index. So for example let’s assign a value of ‘Blur’, array position 1 to a variable.

$variable = $array[1]

Simple right? Now for the clever bit, or I certainly thought it was when I discovered it.

What if we want to reference positions 1 and 3 and put them into a separate array and create a subset of the original array, can we do that?

Well yes we can, check out the following code…

$subset = $array[1,3]

That now creates a new array with in this case the values, Blur and Supergrass.

We could do the same with three elements if we wanted to…

$subset = $array[1,3,4]

Cool huh?

We can also reference a range. Check out the below code that will create a subset of all elements from 2 to 4 inclusive.

$subset = $array[2..4]

So there you go, that might be obvious but I didn’t know about it and thought it was a neat trick when I found it.

One thought on “T-SQL Tuesday #127 – Non SQL Tips and Tricks, Referencing Multiple PowerShell Array Elements

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: