2017-09-24 86 views
1

我有一个PowerShell脚本,其中包含一个$arrayip$hash。我想将$arrayip的每个IP地址添加到我的$hash哈希表中作为名称或密钥。将每个阵列对象添加到HashTable中

我的错误的语法:

$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

+4

什么是你想要的结果?你希望地址是你的散列表中的键或值吗?这是一个根本的区别。一旦拥有这些地址,你想要做什么? –

+0

是的先生,我想添加每个IP作为一个关键,并且值是相同的 – SchoolforDesign

回答

0

这将创建一个散列的数组,但是,你仍然需要思考在hash中放入“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; 
} 
+1

当我在控制台中键入$哈希,为'IP'返回一个值,我想为每个值添加每个IP,例如: ip ----- 192.168.1.1 ip ----- 192.168.1.2 ip ----- 192.168.1.3 name ----- name – SchoolforDesign

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

谢谢你,蒂姆。

+0

控制台中的$ hash键包含一个值!,i想要为每个IP添加每个密钥,例如: ip ----- 192.168.1.1 ip ----- 192.168.1.2 ip ----- 192.168.1.3名称-----名称 – SchoolforDesign

+1

我有更新了我的答案以在名称列下添加IP。我还添加了[排序],以便姓名列始终位于第一位。 –

+0

你使用这个技巧:写输出(新对象 - 类型名称PSObject - 属性$哈希)... 请你可以在你的控制台写$哈希? 那你看到了什么? (名称和服务器IP) 现在我想添加每个ips作为密钥或$ hash的名称 我不想要New-Object sir – SchoolforDesign

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' 
}