Reputation: 839
So I have the following ArrayList stored in $var
:
ip_prefix region string 0.0.0.0/24 GLOBAL Something 0.0.0.0/24 GLOBAL Something 0.0.0.0/24 GLOBAL Something 0.0.0.0/24 GLOBAL Something
I need to add a row to this however the following code returns an error:
$var.add("127.0.0.1/32", "GLOBAL", "something")
Error:
Cannot find an overload for "Add" and the argument count: "3". At line:1 char:1 + $awsips.add("127.0.0.1/32", "GLOBAL", "SOMETHING") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest
I'm sure it's something simple I have to adjust, however Google searches had me going around in circles.
Upvotes: 2
Views: 6577
Reputation: 437618
Your output suggests that your array list contains custom objects with properties ip_prefix
, region
, and string
.
You therefore need to add a single object with the desired property values to your array list.
By contrast, you attempted to add 3 indvividual elements to the array list, which is not only conceptually wrong, but also fails syntactically, given that the .Add()
method only accepts a single argument (technically, there is a method for adding multiple items, .AddRange()
).
In PSv3+, syntax [pscustomobject]@{...}
constructs a custom object from a hashtable literal with the definition order of the entries preserved.
$null = $var.Add(
[pscustomobject] @{ ip_prefix="127.0.0.1/32"; region="GLOBAL"; string="something" }
)
Note how $null = ...
is used to suppress the .Add()
method's output (the index at which the item was inserted).
SQLAndOtherStuffGuy's answer is on the right track, but beware that $var += ...
silently replaces the array list stored in $var
with a regular PowerShell array ([System.Object[]]
).
Upvotes: 2
Reputation: 214
Should do the job
$obj = New-Object PSObject -Property @{
ip_prefix = "0.0.0.0/24"
region = "GLOBAL"
string = "Something"
}
$var+= $obj
Upvotes: 3
Reputation: 43499
$var = New-Object System.Collections.ArrayList
$var.Add(@{"ip_prefix" = "0.0.0.0/24"; "region" = "GLOBAL"; string = "Something"})
$var.Add(@{"ip_prefix" = "127.0.0.1/32"; "region" = "GLOBAL"; string = "SOMETHING"})
$var
$var | %{ Write-Output "$($_.ip_prefix), $($_.region), $($_.string)" }
Or:
$var = @()
$var += @{"ip_prefix" = "0.0.0.0/24"; "region" = "GLOBAL"; string = "Something"}
$var += @{"ip_prefix" = "127.0.0.1/32"; "region" = "GLOBAL"; string = "SOMETHING"}
Upvotes: 4