Powershell - Hashtables
Hashtable memorizza le coppie chiave / valore in una tabella hash. Quando si utilizza una tabella hash, si specifica un oggetto che viene utilizzato come chiave e il valore che si desidera collegare a quella chiave. Generalmente abbiamo usato String o numeri come chiavi.
Questo tutorial introduce come dichiarare le variabili hashtable, creare hashtable ed elaborare hashtable usando i suoi metodi.
Dichiarazione di variabili hashtable
Per utilizzare una tabella hash in un programma, è necessario dichiarare una variabile per fare riferimento alla tabella hash. Ecco la sintassi per dichiarare una variabile tabella hash:
Sintassi
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{}
Note- È possibile creare dizionari ordinati utilizzando una sintassi simile. I dizionari ordinati mantengono l'ordine in cui vengono aggiunte le voci mentre le tabelle hash non lo fanno.
Esempio
I seguenti frammenti di codice sono esempi di questa sintassi:
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}
Stampa la tabella hash.
$hash
Produzione
Name Value
---- -----
ID 1
Color Blue
Shape Square
È possibile accedere ai valori della tabella hash tramite keys.
> $hash["ID"]
1
Elaborazione di Hashtable
La notazione punto può essere utilizzata per accedere a chiavi o valori di tabelle hash.
> $hash.keys
ID
Color
Shape
> $hash.values
1
Blue
Square
Esempio
Ecco un esempio completo che mostra come creare, inizializzare ed elaborare una tabella hash:
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
write-host("Print all hashtable keys")
$hash.keys
write-host("Print all hashtable values")
$hash.values
write-host("Get ID")
$hash["ID"]
write-host("Get Shape")
$hash.Number
write-host("print Size")
$hash.Count
write-host("Add key-value")
$hash["Updated"] = "Now"
write-host("Add key-value")
$hash.Add("Created","Now")
write-host("print Size")
$hash.Count
write-host("Remove key-value")
$hash.Remove("Updated")
write-host("print Size")
$hash.Count
write-host("sort by key")
$hash.GetEnumerator() | Sort-Object -Property key
Questo produrrà il seguente risultato:
Produzione
Print all hashtable keys
ID
Color
Shape
Print all hashtable values
1
Blue
Square
Get ID
1
Get Shape
print Size
3
Add key-value
Add key-value
print Size
5
Remove key-value
print Size
4
sort by key
Name Value
---- -----
Color Blue
Created Now
ID 1
Shape
Square