As I need to be able to add and remove items from an array I need to cast it as an ArrayList
as opposed to the more common options ([string[]]
, [Array]
, $Var=@()
). I also need to preset it with data, but the caller of the function needs the ability to change the preset as they desire. The preset in the Param()
block is required as another entity is looking for preset data. I've tried several variations, but here's the one that makes the most sense:
Function Test-Me{
Param
(
$Properties = [System.Collection.ArrayList]@(
"red",
"blue",
"green")
)
$Properties.GetType()
$Properties.Add("orange")
}
The above is great except that as soon as someone calls Test-Me -Properties "Purple","Yellow","Black"
the $Properties
variable becomes a standard Array
type (whereby add and remove methods don't work).
I tried methods of changing how I declared the preset values. It appears that the act of pre-populating is converting the type to a regular array. I figured this was because I was using @()
with the presets so I've tried ()
as well.
This doesn't work either:
Param
(
[System.Collection.ArrayList]
$Properties = @("red",
"blue",
"green")
)
I have a work around which converts the type outside the Param block and it looks like this:
Function Test-Me{
Param
(
[String[]]
$Properties = @("red",
"blue",
"green")
)
if("Orange" -notin $Properties){
[System.Collections.ArrayList]$Properties = $Properties
$Properties.Add("orange")
}
}
I feel like I should be able to cast as an ArrayList
in the param block and preset it with data, and return as the same datatype, but I couldn't figure it out. If anyone does, or finds documentation why it won't work, please answer.