【问题标题】:Add Each Array Object to HashTable将每个数组对象添加到 HashTable
【发布时间】:2017-09-24 09:28:51
【问题描述】:

我有一个 PowerShell 脚本,其中包含 $arrayip$hash。我想将 $arrayip 中的每个 IP 地址添加为我的 $hash 哈希表中的名称或键。

我的语法错误:

$arrayip = @("192.168.1.1", "192.168.1.2", "192.168.1.3")
$hash = @{
    name = "Name"
    $arrayip = "Is a server IP"
}

对我来说结果不好:

PS C:\> $哈希 名称 值 ---- ----- 姓名 姓名 {192.168.1.1, 192.168.1.2, ... 是服务器IP

【问题讨论】:

  • 你想要的结果是什么?您希望地址成为哈希表中的键还是值?这是一个根本的区别。保存地址后,您想对哈希做什么?
  • 是的,先生,我想将每个 ip 添加为键,并且值相同

标签: windows powershell hashtable


【解决方案1】:

这是你的意思吗?

$arrayips = @("192.168.1.1", "192.168.1.2", "192.168.1.3")

$foreachhash = foreach($arrayip in $arrayips)
{
    $hash = [ordered]@{'Name'=$arrayip;
                       'Is a server IP' = $arrayip
                      } #end $hash

    write-output (New-Object -Typename PSObject -Property $hash)
} #end foreach

$foreachhash

生产:

谢谢,蒂姆。

【讨论】:

  • 控制台中的$hash键包含一个值!,我想为每个IP添加每个键,例如:ip-----192.168.1.1 ip-----192.168.1.2 ip-----192.168.1.3 name-----name
  • 我已更新我的答案以在名称列下添加 IP。我还添加了 [ordered],以便 Name 列始终位于首位。
  • 哦,键值对?从此链接technet.microsoft.com/en-us/library/ee692803.aspx 密钥需要是唯一的。 $arrayips = [有序]@{"IP1" = "192.168.1.1"; “IP2”=“192.168.1.2”; "IP3" = "192.168.1.3"} 如果你然后检查 $arrayips 它会看起来像我想你问的那样。
  • 另一个选项是为整个 foreach 循环设置一个变量。然后显示那个。格式化作为评论可能有点奇怪。 $foreachhashes = foreach($arrayip in $arrayips) { $hash = [ordered]@{'Name'='IP'; '是服务器 IP' = $arrayip } #end $hash write-output (New-Object -Typename PSObject -Property $hash) } $foreachhashes
  • cmets 后更新答案。
【解决方案2】:

要将数组元素作为键添加到现有哈希表中,您可以执行以下操作:

$arrayip = '192.168.1.1', '192.168.1.2', '192.168.1.3'
$hash    = @{ 'Name' = 'Name' }

$arrayip | ForEach-Object {
    $hash[$_] = 'Is a server IP'
}

【讨论】:

    【解决方案3】:

    这将创建散列数组,但是,您仍然需要考虑在散列中的“名称”属性中放入什么。

    # declare array of ip hashes
    $iphashes = @();
    # for each array ip
    for($i = 0; $i -lt $arrayip.Count; $i++){
        $hash = @{
            name = "Name";
            ip = $arrayip[$i];
        }
        # add hash to array of ip hashes
        $iphashes += $hash;
    }
    

    【讨论】:

    • 当我在控制台输入$hash,为'ip'返回一个值,我想为每个值添加每个IP,例如:ip-----192.168.1.1 ip--- --192.168.1.2 ip-----192.168.1.3 名字-----名字
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2022-01-13
    • 2018-09-06
    • 2019-01-25
    • 1970-01-01
    相关资源
    最近更新 更多