Why doesn't the .NET Framework ArrayList class .Add method work in a PowerShell implementation?
I was seeking to return a list of dates from a function as an array with a user-defined date range as parameters. The array of dates would then be referenced to move and read files that are named with date stamps. Creating a dynamic array I was incorrectly calling a .NET .Add method on an @() array declaration.
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
I thought I needed to find a dynamic array type. I discovered that objects should be added to PowerShell arrays using the += syntax. I found the .NET ArrayList class. Now I had a dynamic array object. Documentation said I should use the .Add method to add elements to the collection. It produced a date range but I observed weird dates returned, such as:
Monday, January 1, 0001 12:00:00 AM
To add an element to a .NET ArrayList in Powershell use the .Add method. It's documented. Why doesn't this work? I could obtain accurate results by using the += method for adding objects to an ArrayList. It will produce the errors I described:
Function Get-DateRangeList {
[cmdletbinding()]
Param (
[datetime] $startDate,
[datetime] $endDate
)
$datesArray = [System.Collections.ArrayList]@() # Second method
for ($d = $startDate; $d -le $endDate; $d = $d.AddDays(1)) {
if ($d.DayOfWeek -ne 'Sunday') {
$datesArray.Add($d)
}
}
Return $datesArray
}
# Get one week of dates, ending with yesterday's date
$startDate = Get-Date
$endDate = $startDate.AddDays(-1) # Get yesterday's date as last date in range
$startDate = $endDate.AddDays(-7) # Get 7th prior date as first date in range
$datesList = Get-DateRangeList $startDate $endDate
# Loop through the dates
Foreach ($d in $datesList) {
# Do something with each date, e.g., format the date as part of a list
# of date-stamped files to retrieve
$d
}
ArrayList.Addreturn index of added element and as PowerShell return anything even withoutreturnstatement it return that index, you have eliminate that someway:[void]$datesArray.Add($d).+=does not add elements toArrayList:$a=New-Object Collections.ArrayList;$a+=1;$a.GetType(), so your second example does not work withArrayListbut with array, same as the first one. And, IMHO, do not use@(1, 2, 3, "A", "B", "C"):(1, 2, 3, "A", "B", "C")produce same result, take one character less to type and does not make unnecessary array copy.