将每个数组对象添加到HashTable

时间:2017-09-24 09:28:52

标签: windows powershell hashtable

我有一个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:\> $hash

Name                           Value                                           
----                           -----                                           
name                           Name                                            
{192.168.1.1, 192.168.1.2, ... Is a server IP

image result

3 个答案:

答案 0 :(得分: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

产地:

enter image description here

谢谢,蒂姆。

答案 1 :(得分:0)

这将创建一系列哈希值,但是,你仍然需要考虑放入什么内容" name"哈希的财产。

# 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;
}

答案 2 :(得分:0)

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

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

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