How to create dynamic array in PowerShell?
There are two types of arrays in PowerShell.
- Fixed array
- Dynamic Array
Fixed Array
Fixed arrays are the ones whose values cannot be removed or added. Their sizes are fixed. For example, below is the fixed-size array.
$array1 = @("Cat","Dog","Cow")
If you try to add/remove elements, it will fail.
$array1.add("Tiger")
Some programs you write may need the array dynamically allocated so the elements can be added or removed when needed.
ArrayList
This dynamic array is called the arraylist in PowerShell. There are two ways to create dynamic arrays (ArrayList).
$array2 =New-Object -TypeName 'System.Collections.ArrayList'
OR
[System.Collections.ArrayList]::new()
Let’s check its data type.
This means it is ArrayList, not the Object[]. So dynamic allocation is possible.
Let’s add entries.
$array2.Add("Dog")
$array2.Add("Cow")
$array2.Add("Cat")
Remove the entry.
$array2.Remove("Cow")
There are also many other methods supported to work efficiently with Arrays.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=net-8.0#methods