Pergunta

Eu estou escrevendo uma função que retorna um id, nome par.

Eu gostaria de fazer algo parecido

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

como é possível em javascript. Ou pelo menos

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

como é possível em php. Eu posso fazer isso com o PowerShell?

Foi útil?

Solução

também

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

ou

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

Outras dicas

Sim. Use a seguinte sintaxe para criá-los

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

Irá adicionar também o caminho para percorrer hashtable, como eu estava olhando para a solução e não encontrou um ...

$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

Você também pode fazer isso:

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

Não matriz associativa, mas igualmente útil.

-Oisin

Eu uso isso para manter o controle de sites / diretórios quando se trabalha em vários domínios. É possível inicializar a matriz quando declarar que em vez de adicionar cada entrada separadamente:

$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       

Assim, uma tabela hash é uma matriz associativa. Ohhh.

Ou:

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

Criar a partir de JSON string

$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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top