Home/PowerShell/Powershell Array

Powershell Array

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. The data elements of a PowerShell array need not be of the same type, unless the data type is declared (strongly typed). However, if you think to restrict an array to a certain data type then you can declare the array as like below:

From the above code snippet, $scoreRange will print like one by one manner. Notice that a above declaration is insufficient. You also have to assign values to the variable. If the data types don’t match then it will throw an error.

Output:

In alternatively we can also use the below script for assigning the consecutive numerical values.

Simplified Syntax:

We can explicitly declare the array as like below

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:

In many cases, you won’t assign values manually to an array. Instead, you will want to store the output in a variable. If the output is an array, there we can use above empty array explicitly.

Add elements to an array

If you later want to add elements to an array then you want to use operator “+” .

This can also be written as below. And we can also combined the array.

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 just enter the variable name to make them display all values of the array. As like other programming language, we can able access the value by its index like below:

Example

READ  PowerShell - Replacement Operator

Leave A Comment