質問

私は、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