Blog Post

Arrays in PowerShell–#SQLNewBlogger

,

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

This isn’t necessarily an expert post, but more a recognition that I learned something. I knew about objects in PowerShell, but I’d never actually used an array. Never had a need.

However, while writing my article about striped backups, I ended up using arrays. This was mainly from the example shown by Anthony Notencino in his Restoring Backups from Azure Blob with dbatools.

Here’s a way to initialize an array:

$a = @()

If I look at this, I get nothing back, which makes sense. There’s nothing in there.

2019-10-10 14_41_05-cmd - powershell

I can “add” values to this array with +, as in:

$a += 1

$a += 2

If I now look at the variable, I see this:

2019-10-10 14_44_41-cmd - powershell

One interesting thing here is that += is different than Add(). Look at this:

2019-10-10 14_52_15-cmd - powershell

So why does += work? In the array doc, there’s this quote:

When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value. This might cause performance issues if the operation is repeated several times or the size of the array is too big.

Worth knowing this. I think for most scripts this isn’t a big issue, but be aware that you are allocating a new array.

Working with arrays is a topic for another day, but this is a short look at how you might store something like a list of files in a single place.

SQLNewBlogger

While working on solving the problem for a customer, I realized this was a little thing I learned. A quick post to show that here, just about 10 minutes or writing and structuring code.

A good chance to give an interviewer something to ask you. Write your own post on arrays.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating