我写返回一个ID,名称对的功能。

我想这样做。

$a = get-name-id-pair()
$a.Id
$a.Name

喜欢的是可能在JavaScript。或至少

$a = get-name-id-pair()
$a["id"]
$a["name"]

喜欢的是可能在PHP。我能做到这一点使用PowerShell?

有帮助吗?

解决方案

$a = @{'foo'='bar'}

$a = @{}
$a.foo = 'bar'

其他提示

是。使用以下语法来创建它们

$a = @{}
$a["foo"] = "bar"

也将添加的方式,通过哈希表进行迭代,因为我一直在寻找解决方案,并没有找到一个...

$c = @{"1"="one";"2"="two"} 
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g]
#Define an empty hash
$i = @{}

#Define entries in hash as a number/value pair - ie. number 12345 paired with Mike is   entered as $hash[number] = 'value'

$i['12345'] = 'Mike'  
$i['23456'] = 'Henry'  
$i['34567'] = 'Dave'  
$i['45678'] = 'Anne'  
$i['56789'] = 'Mary'  

#(optional, depending on what you're trying to do) call value pair from hash table as a variable of your choosing

$x = $i['12345']

#Display the value of the variable you defined

$x

#If you entered everything as above, value returned would be:

Mike

您也可以这样做:

function get-faqentry { "meaning of life?", 42 }
$q, $a = get-faqentry 

不关联数组,但同样是有用的。

-Oisin

我用这个跟踪的网站/目录多个域上工作时。是可能的初始化数组声明它时,而不是分别添加各项:

$domain = $env:userdnsdomain
$siteUrls = @{ 'TEST' = 'http://test/SystemCentre' 
               'LIVE' = 'http://live/SystemCentre' }

$url = $siteUrls[$domain]
PS C:\> $a = @{}                                                      
PS C:\> $a.gettype()                                                  

IsPublic IsSerial Name                                     BaseType            

-------- -------- ----                                     --------            

True     True     Hashtable                                System.Object       

因此,一个散列表是一个关联数组。哦~~。

或者:

PS C:\> $a = [Collections.Hashtable]::new()

创建从JSON字符串

$people= '[
{
"name":"John", 
"phone":"(555) 555-5555"
},{
"name":"Mary", 
"phone":"(444) 444-4444"
}
]';

# Convert String To Powershell Array
$people_obj = ConvertFrom-Json -InputObject $people;

# Loop through them and get each value by key.
Foreach($person in $people_obj ) {
    echo $person.name;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top