That’s where arrays come in. Be it C++ or Python, arrays are present in every programming language in some form. But what about Windows PowerShell? How do PowerShell arrays work? How do you use them? What is their syntax? Let’s find out.
PowerShell Arrays 101
Simply speaking, an array is just a structured collection of variables. The idea is to eliminate the hassle of keeping track of dozens of names by collapsing related variables into a numbered set. In PowerShell, you can create a variable by prepending the $ symbol to a variable name. For example: $prime = 13 The variable can contain any data type, from numbers to strings. You just need to use double or single quotes to specify a string. $name = “Levin” Now to create a new array, simply assign multiple values to the same variable, separated by commas. Like this: $week = “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” Some people prefer to explicitly cast a variable into an array to avoid confusion, though that isn’t necessary. To do this, put the values into parentheses prefaced with the @ symbol. $week = @(“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”) This usually comes in handy when trying to put the output of other commands into an array, where you cannot manually write them in the correct format.
Creating an Array
We’ve already seen the most common method of creating an array. But depending on the situation, there are other ways that might be more suitable. For example, if you want to create an array that contains a range of numbers, you can use the range operator: $digits = (0..9) This will create an array of all the ten digits from zero to nine. You can also initialize an empty array, in case you just want a place to store values later. $values = @() Multiple arrays can even be nested into one another, though this type of usage can get confusing very fast. $coordinates = @( (5, 10, 23), (11, 7, 16)) By default an array can store any variable type, be it numbers, strings, or a mix of both. But you can explicitly define a type in case you want to limit the values put in it. For example: [int[]] $numbers = 2,3,4,5 This way, the array can only hold integers. Attempting to assign any other type of value to it will return an error. This can be useful to prevent simple errors for arrays exclusively working with numeric values, since entering a string into a variable to be used in calculations will create issues.
Accessing Arrays
So far we have seen multiple methods for creating arrays containing various types of data. But how do you go about accessing this data? PowerShell arrays use the same format used by other programming languages. Each array variable can be accessed by its index number. For example: $var = $numbers[5] This will copy the value stored in the index five of the $numbers array in the $var variable. Note that array indices start counting from 0, so the first item is accessed with zero. If we were to output this, for example: “$days[2]” We will get Wednesday, not Tuesday. You can use this same method to modify these values as well. For example, the following command will change the second element of the array to zero: $numbers[1] = 0 You can also add more elements to an existing array instead of changing the values of current entries just by adding them like an arithmetic expression. $names += “Johny” This method can be used to add multiple entries at once too, or even entire arrays. $names += “Charlie, Liam, Teresa” $names += $surnames The comma-separated method holds for accessing multiple array elements too. Entering this, for example, stores the first five elements of $days in $weekdays. $weekdays = $days[0,1,2,3,4]
Iterating Through Arrays
Manually accessing particular elements of an array is well and good, but if you want to perform actions on the entire contents of an array, it can get tedious. A more elegant approach is to use a For loop. For loops can systematically go through all the elements of an array, processing each value according to instructions. This is how you can construct such a loop: For ($i = 0 ; $i -lt $days.Length ; $i++){ $days[$i]} The array.Length function returns the size of the array, which is basically the number of elements in it. This can be plugged into a For loop’s test expression parameter to comprehensively iterate over all the elements. The Foreach loop and the Foreach-object loop can do the same with an even leaner PowerShell script. Foreach ($day in $days){ $day} This saves you the effort of determining the array’s size, leaving the details for PowerShell to handle.
When Should You Use PowerShell Arrays
The biggest source of bugs in a complex script is incorrectly referenced variables. This happens due to the presence of a large number of uniquely named variables, which makes it difficult to remember their purpose. The simplest fix for this issue is to use arrays extensively. All variables related in some manner can be assigned to a single array and accessed through their index numbers. Microsoft PowerShell’s prime use case is automation, and arrays play a pivotal role in that. The objects returned by PowerShell cmdlets can be stored into arrays and iterated over. This allows sequential tasks to be performed automatically, greatly simplifying system administration.