Arrays 向ArrayList添加新的值集
因此,我将以下ArrayList存储在Arrays 向ArrayList添加新的值集,arrays,windows,powershell,arraylist,Arrays,Windows,Powershell,Arraylist,因此,我将以下ArrayList存储在$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 错误: Cannot find an overload for "Add" a
$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
错误:
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
找不到“Add”和参数计数的重载:“3”。
第1行字符:1
+$awsips.add(“127.0.0.1/32”、“全球”、“某物”)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo:NotSpecified:(:)[],MethodException
+FullyQualifiedErrorId:MethodCountNotFindBest
我相信这很简单,我必须调整一下,但是谷歌搜索让我兜了一圈。应该可以完成这项工作
$obj = New-Object PSObject -Property @{
ip_prefix = "0.0.0.0/24"
region = "GLOBAL"
string = "Something"
}
$var+= $obj
或:
您的输出表明,您的数组列表包含具有属性
ip\u前缀
、区域
和字符串的自定义对象
因此,需要将具有所需属性值的单个对象添加到数组列表中
相比之下,您尝试向数组列表添加3个Individual元素,这不仅在概念上是错误的,而且在语法上也是失败的,因为数组列表只接受一个参数(从技术上讲,有一种方法可以添加多个项,.AddRange()
)
在PSv3+中,语法[pscustomobject]@{…}
从哈希表文本构建自定义对象,保留条目的定义顺序
$null = $var.Add(
[pscustomobject] @{ ip_prefix="127.0.0.1/32"; region="GLOBAL"; string="something" }
)
请注意如何使用$null=…
来抑制.Add()
方法的输出(插入项的索引)
在正确的轨道上,但是请注意,$var+=…
会用常规PowerShell数组([System.Object[]]
)以静默方式替换存储在$var
中的数组列表。看看这里。看起来您正在添加到对象数组中。因此,在添加{…}
->[PSCustomObject]{…}
时,您需要设置新对象的属性。这是正确的方法,但我会使用PSObject
而不是object
,并将属性列表作为哈希表传递给新对象,而不是单独添加每个属性。在PowerShell v3及更新版本上,选择的方法是直接在属性哈希表上使用[PSCustomObject]
类型加速器。好建议。我修改了代码以反映这一点。
$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)" }
$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"}
$null = $var.Add(
[pscustomobject] @{ ip_prefix="127.0.0.1/32"; region="GLOBAL"; string="something" }
)