PowerShell multidimensional arrays are one of the complex data types in PowerShell. It can store data without having to save it to the secondary storage.
People Also Search for:
Just like most other programming languages, the multi-dimensional array is an extension of the array. An array can store different individual data and we need to understand how an array works before we learn how a multi-dimensional array works.
Simple Array Syntax:
The simple array syntax will help us see how an array is made. The following script will create an array in PowerShell.
Clearly the above given is an array of string. We can also create an array of numbers as shown below.
The array saved in the $arrnum is shown in the image below.
We can check the type of the variable using the gettype() method. Here is the syntax for that.
We can store numbers and strings together in one array. For example,
Introduction to Multidimensional arrays:
The multidimensional arrays are an extension of the single dimension arrays. It is a table where each cell has an index of its own. There are a few different methods to create a multidimensional array.
We can create a null array and add elements to it. We can create a null array using the following syntax.
Every time we add an element to this array, PowerShell creates a new array will all the existing elements and adds the new element to the new array and destroys the old array. This is a necessary process as the structure information is not available during the time of declaration. There will be poor performance if there are millions of rows to work with.
Another way to create a multidimensional array is by providing the number of rows and columns information. Here is the syntax for creating an array with 3 rows and 4 columns.
We can check the data type of the variable and see that it is a multidimensional array.
We will add a row to the array using the below script. Note that there is a comma, (,) in the beginning because the comma is needed to tell PowerShell that each one of them is in a new row.
We will add another row in the following way.
Now we will write the contents of the array using the following script.
The above script will print the elements of the array on to the console and the output of the above script is shown below.
We can use the multidimensional array to store data in matrix form. It can be created using a null array but every time a new element is added to the array, the array is recreated and so it will have poor performance when there are more elements. Another way of doing this is to have the structure pre-defined and add the elements subsequently.
If you want to know more about multidimensional arrays in PowerShell, stay tuned to TecKangaroo.
Powershell Multidimensional Array
- Author Rating
- Content Clarity
- Content Relevance
- Article Rating