Ha powershell ha array associativi?
-
19-09-2019 - |
Domanda
Sto scrivendo una funzione che restituisce un id, coppia nome.
Mi piacerebbe fare qualcosa di simile
$a = get-name-id-pair()
$a.Id
$a.Name
come è possibile in javascript. O almeno
$a = get-name-id-pair()
$a["id"]
$a["name"]
come è possibile in php. Posso farlo con PowerShell?
Soluzione
anche
$a = @{'foo'='bar'}
o
$a = @{}
$a.foo = 'bar'
Altri suggerimenti
Sì. Utilizzare la seguente sintassi per crearli
$a = @{}
$a["foo"] = "bar"
Aggiungerà anche il modo per scorrere hashtable, mentre stavo cercando la soluzione e non ho trovato una ...
$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
È anche possibile fare questo:
function get-faqentry { "meaning of life?", 42 }
$q, $a = get-faqentry
Non array associativo, ma altrettanto utile.
-Oisin
Io lo uso per tenere traccia dei siti / directory quando si lavora su più domini. È possibile inizializzare l'array quando dichiara piuttosto che aggiungere ogni voce separatamente:
$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
Quindi, una tabella hash è un array associativo. Ohhh.
o
PS C:\> $a = [Collections.Hashtable]::new()
Crea da JSON Stringa
$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;
}