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:

[int[]] $scoreRange = 1,2,3,4,5,6,7,8,9
$scoreRange

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.

[int[]] $$scoreRange = 1 .. 9
$scoreRange

Simplified Syntax:

We can explicitly declare the array as like below

$myFavFruits= @("Banana","Orange","Apple","Mango")

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:

$myFavFruits = @()

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 “+” .

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
$myFavFruits

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

$myFavFruits += "orange"
#Combined Array
$myFavFruits += $yourFavFruits

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

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
#Display the list of furits
Write-Host "";
Write-Host "List of my favorite fruits are $myFavFruits "
Write-Host "";
Write-Host "Most favorite fruit is" $myFavFruits[1]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.