将每个数组对象添加到哈希表

Add Each Array Object to 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

这将创建散列数组,但是,您仍然需要考虑将什么放入 "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;
}

你是这个意思吗?

$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

产生:

谢谢,蒂姆。

要将数组元素作为键添加到现有哈希表中,您可以这样做:

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

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