【问题标题】:Simple PowerShell question - How to convert object into arraylist简单的 PowerShell 问题 - 如何将对象转换为 arraylist
【发布时间】:2018-10-28 02:13:46
【问题描述】:

我有一个包含以下内容的变量:

Site                      IP

walmart                   10.20.30.40
walmart                   10.20.30.41
walmart                   10.20.30.42
target                    10.20.30.50
target                    10.20.30.51
hm                        10.20.30.60

这是一个使用New-Object psobject -Property @{ site = <code> ; IP = <code> } 创建的对象。所以如果我打电话给$obj.site,它只会列出站点,IP 也是如此。

我想把它转换成一个由站点分组的数组列表。

例如,结果输出应如下所示:

walmart     :  {10.20.30.40, 10.20.30.41, 10.20.30.42}
target      :  {10.20.30.50, 10.20.30.51}
hm          :  {10.20.30.60}

我希望能够从我的脚本中调用它,例如在任何站点上添加或减去 IP。例如:

$myArray.target 

应该列出如下 IP:

10.20.30.50
10.20.30.51

而不是同样的格式——{10.20.30.50, 10.20.30.51}

然后我会使用 Add 方法向这些对象添加更多 IP。

($myArray.walmart).Add("10.20.30.44")

我能得到的最接近的是以下(及其输出):

$obj | Group-Object -Property Site | Select-Object Name,Group

Name            Group

walmart         {@{Site=walmart; IP=10.20.30.40}, @{Site=walmart; IP=10.20.30.41}, @{Site=walmart; IP=10.20.30.42}
target          {@{Site=target; IP=10.20.30.50}, @{Site=target; IP=10.20.30.51}
hm              {@{Site=hm; IP=10.20.30.60}

使用该输出,我无法访问特定站点,例如 $myArray.walmart

我对 powershell 很陌生,我错过了什么?任何帮助将不胜感激!

【问题讨论】:

  • 你看过使用哈希表吗?这使您可以拥有唯一的键 [站点] 和可以是单例或数组的值。它使查找站点信息变得非常快...$LookupTable['SiteName'] 将为您提供所有 IP。然后$LookupTable['SiteName'][0] 会在该键的值中为您提供项目数组中的第一项。

标签: arrays powershell object arraylist grouping


【解决方案1】:

试试这样的:

$Array=@(
[pscustomobject]@{Site='walmart'; ID='10.20.30.40'}
[pscustomobject]@{Site='walmart'; ID='10.20.30.41'}
[pscustomobject]@{Site='walmart'; ID='10.20.30.42'}
[pscustomobject]@{Site='target'; ID='10.20.30.50'}
[pscustomobject]@{Site='target'; ID='10.20.30.51'}
[pscustomobject]@{Site='hm'; ID='10.20.30.60'}
)

$Object=New-Object PSObject

$Array | group Site | %{

#create an new list with all id for the curretn group
$CurrentList = New-Object System.Collections.Generic.List[System.Object]
$_.group.ID | %{$CurrentList.Add($_)}

#Add property and list to the final object
Add-Member Noteproperty -Name $_.Name -value $CurrentList -InputObject $Object
}

#add element to a site
$Object.hm.Add("NewID")

【讨论】:

  • 谢谢@Esperento57!这帮助很大!
猜你喜欢
  • 1970-01-01
  • 2016-01-24
  • 2014-08-28
  • 1970-01-01
  • 2020-10-29
  • 2014-11-10
  • 2011-02-08
  • 2021-07-15
  • 2019-08-17
相关资源
最近更新 更多