- Delegate permissions for domain join - Mon, Jun 5 2023
- Join Windows 11 to an Active Directory domain - Thu, Jun 1 2023
- Change Windows network profiles between public and private - Wed, May 24 2023
Unlike in strongly typed languages, such as C or Java, in PowerShell you don’t have to declare a variable as an array. It is sufficient to add values in the correct way to automatically transform a variable into an array. However, one exception is handling arrays that you want to restrict to one data type.
Work with data types
By default, PowerShell assumes that the elements of an array are of the type variant. This means that you can mix different data types—that is, combine numerical values, dates, or strings in a single variable. However, if you want to restrict an array to a certain data type, you can declare the array in the following way:
[int[]] $e = 1,2,3,4,5,6,7,8,9
Notice that a mere declaration is insufficient. You also have to assign values to the variable. If the data types don’t match, PowerShell will throw an error.
An elegant alternative for assigning consecutive numerical values is the use of the range operator, which allows you to simplify the above command:
[int[]] $e = 1 .. 9
Assign values to an array
The first example demonstrates how to explicitly assign values to an array using the so-called simplified syntax. An alternative would be:
$colors = @("black","white","yellow","blue")
Under normal circumstances, you would want to avoid the additional effort of this notation. However, it helps you understand why you can create an empty array in PowerShell with this command:
$colors = @()
In many cases, you won’t assign values manually to an array. Instead, you will want to store the output of a cmdlet in a variable. If the output is an array, it can be tested like this:
(Get-Process) -is [array]
If you only want to store specific properties in the variables, and not the entire output of the command, you can filter the properties with the Select-Object:
$mac = Get-NetAdapter | Select MacAddress
This command would save all MAC addresses of the installed NICs in the variable $mac.
Add elements to an array
If you later want to add elements to an array, you don’t have to call a method because the operator “+” is used for this purpose.
$colors = $colors + "orange"
Or, if you want to use the combined assignment operator, you can rewrite the above example like this:
$colors += "orange"
You can also combine two arrays this way. For instance, if you have another array $pattern with the values “dotted,” “checked,” and “lined,” you could concatenate it to $colors with this command:
$colors += $pattern
Display the contents of an array
If you want to display the elements of an array, you usually don’t need a loop. In the simplest case, it is enough to enter the variable name to make PowerShell display all values of the array.
As in other programming languages, you can access a specific element though the index. As expected,
$colors[0]
displays “black.” It is important to note that, contrary to some BASIC dialects, PowerShell starts counting at zero. PowerShell not only accepts a single index value but also accepts constructs like this:
$colors[1,4,7]
This command would display the array’s second, fifth, and eighth element. You can also use the range operator if you want to display a connected range:
$colors[2 .. 6]
Negative numbers allow you to access the last elements of the array. For instance, this command would display the last element:
$colors[-1]
Correspondingly, -2 would display the next-to-last element.
Find elements
If you want to determine if an array contains a certain value, you don’t have to iterate through elements to compare them with the search term. Rather, you can apply various comparison operators directly to the array.
$colors[0 .. 5] -like "*ck*"
This command would find “black” and “checked.”
Sort arrays
Arranging the elements of an array in a certain order is fairly easy with PowerShell. All you have to do is pipe the output of an array to the Sort-Object cmdlet:
$colors | Sort
Of course, you can leverage the extensive features of the Sort-Object, such as changing the sort order to descending or removing duplicates.
If you want to sort the order not just to display it on the screen but also to store it in the array, you have to assign the elements again:
$colors = $colors | Sort
Delete arrays and elements
Even though most of the array operations in PowerShell are relatively easy to accomplish, no convincing solution exists for removing specific elements or deleting complete arrays. The easiest way to get rid of an entire array is to assign the variable $null:
$colors = $null
If you want to remove specific elements, you need a workaround that filters and reassigns values.
Subscribe to 4sysops newsletter!
$colors = $colors | where {$_ -ne "yellow"}
In this example, the Where-Object would return all elements that are unequal to “yellow” and assign them to the array. The result is that the element with the value “yellow” is removed from the array.
Nice little write-up on the basics. Would be nice to add a bit about how to find the total number of entries in the array. It’s info that comes in handy frequently.
$array.length
hi,
I have a problem with arrays in powershell.beacause i’m newly learner of powershell.can u please give the deep example of arrays initialization with size and with out size declaration,runtime initialization of an array,and how to read runtime initialized elements of an array.
I’ve read a ton of PowerShell tips & tricks and you are far and away the best writer I’ve encountered. Please keep at it!
For what it is worth.. arrays are considered fixed size. Attempting to modify them results in the array being copied and then the additional operation added in as part of that copy. So, lets say I have a += on a 5 element array. That 5 element array gets copied to a 6 element array, and then the new element is added. Performance wise, this is a substantial penalty.
Now.. with small arrays we’re dealing with microseconds, so it’s not really noticeable. But, if the array is going to be changed, it’s easy to replace it with an ArrayList.
You can use it exactly like an array, but it is dynamically sized, and includes a lot of useful methods. Here are just a few of the methods & properties you can use:
and many more.. My understanding of this is that the arrays are more memory efficient (with the fixed size limit, etc.), while the ArrayList has a lot of flexibility.
From a practical perspective in scripts, when you add an element to an ArrayList, there position/index of the new element is returned. So, if you don’t care, you can use the normal [void]($ArrayList.Add()) or $null = $ArrayList.Add() constructs to suppress the return.
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netframework-4.7.2
David F.
I think strict-typed System.Collections.Generic.List is better and faster and no need [void].
@David
There are many ways to manipulate arrays. Wolfgang’s post is very good to help beginners to understand the basic concepts.
Seems like you improved you skills in this domain with Array classes… 😉
However, for information and according to Microsoft (directly in the link you provided).
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1
A little issue with the display…
Here is the quote:
I’ve been purely a Powershell guy (never a real developer).. I’ve never understood the syntax for that one you mention (List<T>).. I’d love to learn more about how that could be used in Powershell.
I liked the original article, my big complaint was the inflexibility for arrays. If you guys can put up some syntax for the other kinds of lists, I’d love to see them and extend it more..
David F.
Ok David, I put that on my to do list.