Organizing and processing your data with PowerShell arrays

Variables and arrays are an integral part of any programming language as they form the building blocks of your code. You use variables to store values, process them, and even possibly display or transfer it to any other part of the program. Variables can hold only a single value at any time. But in the real world, you’re more likely to deal with more than one variable, given the complexity of the systems and the problems that need a solution. In such a case, you need a data structure that will hold a series of values together. PowerShell arrays are a powerful data structure where you can store a set of elements of any type in sequential order. Each element in the array is identified by an index that starts with 0. So, the first value in an array sits at index 0, the second one in index 1, and so on. In this sense, an array is a collection of elements or variables that are arranged sequentially.

Creating PowerShell arrays

As a first step, let’s see how you can create PowerShell arrays.

$myArray = 1,2,3,4,5,6

This simple declaration is enough to tell PowerShell that you intend to create an array with the elements 1 to 6.

Now, if you want to check if PowerShell has indeed created an array, you can do that with this command:

$myArray.getType()

The output will be:

System.Array

Sounds simple, right?

Now, what happens if you want to create an array with just one variable for now with the possibility to add more values later?

Your first guess might be:

$myArray = 1

Fair enough. Now if you type:

$myArray.getType()

The output will be:

System.ValueType

In other words, PowerShell has created a variable instead of an array because there is only one variable and it has assumed that you want to create a variable and assign a value to it.

The good news is there are many ways by which you can tell PowerShell to create an array with a single variable in it.

The easiest option is to use a “,” comma to let PowerShell know what you want.

$myArray = , 1

Now, the output for $myArray.getType() will be System.Array.

If that seems confusing, you can explicitly tell PowerShell that you want to create an array. The syntax for that is:

[object[]]$myArray = 1

When you type this code, PowerShell knows that you want to create an array and will do so for you with one variable in it.

The third way to create an array is:

$myArray = @()

This option allows you to create an empty array. This is a convenient way to initialize an array regardless of how many elements you’ll add to it in the future.

It is important to note that you can choose to create arrays that will only take elements of a certain type. For example, if you want your array to accept only integer values, you can define it like this:

[int32[]]$myArray = 1,2,3

Thus, these are some ways to create a PowerShell array.

Accessing the PowerShell array

Accessing values from a PowerShell array is fairly easy too. For example:

$myArray = 1,2,3,4,5,6

Let’s say, you want to access the first object. All that you have to do is:

$myArray[0]

This will access the first element in your array, which is “1.”

Typically, your array will store variable like this:

$myArray[0] – 1

$myArray[1] – 2

$myArray[2] – 3

$myArray[3] – 4

$myArray[4] – 5

$myArray[5] – 6

You can access the value based on this sequential numbering. If you want all the elements to get printed, simply use $myArray.

Write-output ("All the elements in the array are:")
$myArray

The output will be as depicted in the following screenshot:

powershell arrays

After creating PowerShell arrays, you can assign values directly to a specific location, though it is not a good programming practice to hard-code values directly. Still, it’s an option that can come in handy in some situations. For example, you can say:

$myArray[3] = 8

If you print $myArray, the output will be 1,2,3,8,5,6.

Processing PowerShell arrays

Arrays are a powerful data structure that goes way beyond just storing or accessing values or variables. You can use it in different ways in your program. Let’s take a look at some ways of using these arrays.

Knowing the length of your PowerShell array

Let’s say you’re adding elements to an array dynamically and in the end, you want to know how many elements are present in it. All that you have to do is:

$myArray.Length

This will give you the number of elements, which in our example is 6.

Partial processing

There will be times when you’d want only the first few values of the array and not the entire list. If you know how many elements you want and from which index, you can directly process it like this:

$SmallList = $myArray(2..5)

Now, the array $SmallList will contain the values present in $myArray[2] to $myArray[5], which in our example comes to 3,4,5,6.

Using PowerShell array values in a loop

One of the most useful applications of PowerShell arrays is to run it in a loop where elements are checked or processed sequentially during every iteration.

For example, you can run through all the elements in the array and add a value of 10 to each.

$i = 0
while($i -$myArray.Length) {
$myArray[$i]= $myArray[$i] + 10;
$i++
}

This prints these values: 11, 12, 13, 14, 15, 16, as shown in the screenshot below.

powershell arrays

As you can see, these are different ways to access and process the elements in your PowerShell array.

Advanced uses of PowerShell arrays

The above uses are fairly elementary, but in the real world, you’ll do a lot more with arrays, so here are some examples of advanced uses.

ArrayList

PowerShell has a class called ArrayList that makes it easy to add, remove, or search items in an array.

To use this class, you should first convert your array to the ArrayList class. The code for that is:

$myArray = New-Object System.Collections.ArrayList.

When you execute this code, your array is converted into an ArrayList. If you print $myArray.getType(), the output will be System.Object.

Now you can easily add or remove values from the array.

For example, let’s say, the values of an array called $namesArray are John, Sam, Betty, Laura.

To add another name, all that you have to do is:

$namesArray.Add("Susie")

When you print the values of $namesArray, it will have five elements and the last will be Susie. Note that the value will be added only at the end.

To remove a value:

$namesArray.Remove("Betty")

The output will have John, Sam, Laura, Susie.

You can also search through the array using a method called Contains:

$namesArray.Contains("John")

The output will be “True.”

The above examples show how easy it is to add, remove, or search for elements within an array using a class called ArrayList.

Clearing a PowerShell array

We’ve seen creation, accessing, adding, removing, and a ton of other operations. So, how do you delete an array?

Unfortunately, there’s no easy way in PowerShell to delete an array. Probably, the easiest way is to assign the $null value to it.

$myArray = $null

In PowerShell, if a variable has a null value, you can’t access it or do anything with it. Effectively, this array is nonexistent from a programmer’s standpoint, though PowerShell may still allocate memory for it.

Using methods

There are many built-in methods that make life easy for you. For example, if you want to sort the contents of your array, you don’t have to run it through a loop. A simple sort command will do the job for you.

$namesArray | sort

Of course, this would work only if all the elements in your array belong to the same data type.

You can export your array to a .csv file with this command:

$namesArray | Export-Csv -Path C:\studentnames.csv

You can also write these values to an HTML file with this command:

$namesArray | ConvertTo-Html > C:\studentnames.html

Final thoughts on PowerShell arrays

PowerShell arrays are an important data structure that allows you to do a ton of things, starting from storing values in sequential order to sorting, and even exporting it to other files. We hope this article gives a peek into the world of arrays and enthuses you to try out some real-world programming applications with it.

Featured image: Piqsels

Leave a Comment

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top