2009-10-01 8 views
25

Estoy escribiendo una función que devuelve una identificación, un par de nombres.Does powershell tiene matrices asociativas?

me gustaría hacer algo como

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

gusta es posible en javascript. O al menos

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

como es posible en php. ¿Puedo hacer eso con Powershell?

Respuesta

43

también

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

o

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

comentario viejo, pero la forma en que se recorre a través de una matriz asociativa a través de un bucle foreach? –

+3

$ vector asociativo = @ { Jane = 1 Tom = 2 Harry = 3} foreach ($ clave en associativeArray.Keys $) {$ clave } foreach ($ item en $ asociativeArray.GetEnumerator()) { "{0} = {1}" -f $ item.Key, $ item.Value } × Los comentarios deben tener al menos 15 caracteres de longitud. × Los comentarios deben tener al menos 15 caracteres en longitud. × Los comentarios deben tener al menos 15 caracteres de longitud. –

22

Sí. Utilice la siguiente sintaxis para crearlos

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

También puede hacer esto:

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

No matriz asociativa, pero igualmente útil.

-Oisin

9
#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 
0

lo uso para hacer el seguimiento de los sitios/directorios cuando se trabaja en varios dominios. Es posible inicializar la matriz cuando se declara que en lugar de añadir cada entrada por separado:

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

$url = $siteUrls[$domain] 
3

se sumará también el camino a recorrer tabla hash, como yo estaba buscando la solución y no encontré uno ...

$c = @{"1"="one";"2"="two"} 
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g] 
1
PS C:\> $a = @{}              
PS C:\> $a.gettype()             

IsPublic IsSerial Name          BaseType    

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

True  True  Hashtable        System.Object  

Así una tabla hash es una matriz asociativa. Ohhh.

O:

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