The PowerShell array is one of those staples of scripting I use in nearly every script I write. It's a very easy way to store multiple variables inside a single container. Let's see how we can use Powershell to manage arrays.
Creating an array
First, let's create an array:
$array1 = @()
In this example, I'm simply creating a blank array (an array with no elements) and assigning it to a variable.
PowerShell arrays always started with an ampersand and are enclosed with parentheses.
What if you already know the variables you want to put into the array ahead of time? No problem! Let's create an array and put in 5 integers at the same time.
$array1 = @(1,2,3,4,5)
Now we need to add a few elements to our array. We've got a few different ways to make that happen.
## Create a NEW array 1 element larger than our last and assign it the same name as our old array $array1 += 6 ## Push an element onto our existing array $array1 = $array1 + 6
There might be a few different options you'd be tempted to do but don't. They don't work! Why? Because an array is a fixed size. You can't simply add an element to it without first redefining it.
If you remember the VBscript days, it was UGLY managing arrays because you had to be intimately familiar with redimming the array all the time.
Reading elements from an array
We've now got our array created how do we go about reading it? As always, there's a few different ways to read an array with PowerShell.
The first way is by explicitly giving the index number of the element. Each element inside an array is assigned an index. All arrays are 0-based which means the index always starts with 0. So, for example, if I want the first element, I'd do:
If I wanted the third element I'd do:
Next, we can use the very powerful yet underutilized PowerShell range to get more than one element at a time.
## Will get the first, second and third elements $array1[0..3] ## Using the + operator, we can get the first, second, third and fifth elements at one time $array1[0..3+5]
Finally, let's say we want the last element. In this case, we can utilize a shortcut index number.
## Get the last element $array1[-1] ## Get the second to last element $array1[-2]
Removing elements from an array
..and if you didn't expect this, we can also remove elements from arrays as well albeit not used nearly as often.
## replace the '1' in our original array with test $array1 = 'test'
Join the Jar Tippers on Patreon
It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!Become a Patron!
Subscribe to Adam the Automator
Get the latest posts delivered right to your inbox