By default, PowerShell arrays are fixed size, which makes adding items more difficult than you would expect. Take the following code as an example:
$names = "Paul","John","Peter" $names.Add("Simon")
This generates an error:
This happens because arrays in PowerShell are fixed size. As a work around the above code can be modified:
$names = "Paul","John","Peter" $names += "Simon"
Using this method, the original array is replaced by entirely new array with the existing contents copied into it and the new element added. If your array has many items this will impact performance.
Use an ArrayList instead of a Standard Array
Using an ArrayList is an easier and faster than a standard PowerShell array. Here is an example:
$names = New-Object System.Collections.ArrayList $names.Add("Paul") $names.Add("John") $names.Add("Simon") $names.Remove("Paul")
This method makes it much easier to work with dynamically sized arrays. If you still require a standard PowerShell array you can do:
$PowerShellArray = $names.ToArray()
Hope this helps.
Brian Jenkinsq says
Can you the .Add command to call a function along with using $_? For instance:
$array = [System.Collections.ArrayList]@()
#Fill with a list of devices from a function earlier in script
$array = get_alldevices
#emtpy array
$empty = [System.Collections.ArrayList]@()
$array | Foreach-Object {
$empty.Add(get_detailsfunction $_)
}
Typicall I would have done this like:
$array | Foreach-Object {
$empty += get_detailsfunction $_
}
For large arrays this is VERY slow and not efficient, so I was hoping to use .Add to fill the empty array faster.