PowerShell: How to Create an Array with Initial Size


You can use the following methods in PowerShell to create an array with a specific initial size:

Method 1: Create an Array with Specific Size of Null Values

$my_array = @($null) * 10

This particular example creates an array named $my_array with 10 null elements.

Method 2: Create an Array with Specific Size of Specific Values

$my_array = @(0) * 10

This particular example creates an array named $my_array with 10 elements all equal to the value 0.

Method 3: Create an Array with Specific Size of Repeating Values

$my_array = @(1, 2, 3) * 3

This particular example creates an array named $my_array with 9 total elements by repeating the pattern 1, 2, 3 a total of 3 times.

The following examples show how to use each method in practice.

Example 1: Create an Array with Specific Size of Null Values

We can use the following syntax to create an array named $my_array that contains 10 null elements:

$my_array = @($null) * 10

The following screenshot shows how to use this syntax in practice:

PowerShell create empty array of specific size

Notice that when we view the array there are no values to display since each element in the array is null.

However, when we use the length property we can see that the array contains 10 total elements.

Example 2: Create an Array with Specific Size of Specific Values

We can use the following syntax to create an array named $my_array that contains 10 elements that are all equal to the value zero:

$my_array = @(0) * 10

The following screenshot shows how to use this syntax in practice:

PowerShell create an array with specific size

We can see that this produces an array with 10 total elements in which each element is equal to the value zero.

Example 3: Create an Array with Specific Size of Repeating Values

We can use the following syntax to create an array named $my_array that contains the pattern 1, 2, 3 repeated a total of 3 times:

$my_array = @(1, 2, 3) * 3

The following screenshot shows how to use this syntax in practice:

PowerShell create array of specific size with repeating values

We can see that this produces an array with 9 total elements that repeat the pattern 1, 2, 3 a total of 3 times.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Create an Array of Arrays
PowerShell: How to Check if Input Value Exists in Array
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply