I'm new to powershell and trying to get the length of a HashTable (to use in a for loop), but I can't seem to get the length of the HashTable to output anything.
$user = @{}
$user[0] = @{}
$user[0]["name"] = "bswinnerton"
$user[0]["car"] = "honda"
$user[1] = @{}
$user[1]["name"] = "jschmoe"
$user[1]["car"] = "mazda"
write-output $user.length #nothing outputs here
for ($i = 0; $i -lt $user.length; $i++)
{
#write-output $user[0]["name"]
}
Hash is a number that the hash table uses to get the value. Hash then maps directly to a bucket in the array of key/value pairs. Let’s understand the working of PowerShell through given examples: First, create an empty hashtable and then populate it with the key-value pairs or, You can also create a hashtable and initialize it at the same time.
The keys and values in a hash table can also be Hashtable objects. The following statement adds key/value pair to the hash table in the $p variable in which the key is a string, Hash2, and the value is a hash table with three key/value pairs. PowerShell. C:\PS> $p = $p + @ {"Hash2"= @ {a=1; b=2; c=3}}
You can use hash tables to store lists and to create calculated properties in PowerShell. And, PowerShell has a cmdlet, ConvertFrom-StringData, that converts strings to a hash table. The syntax of a hash table is as follows:
Generally, you think of a hashtable as a key/value pair, where you provide one key and get one value. PowerShell allows you to provide an array of keys to get multiple values. In this example, I use the same lookup hashtable from above and provide three different array styles to get the matches.
@{}
declares an HashTable whereas @()
declares an Array
You can use
$user.count
to find the length
of you HashTable
.
If you do:
$user | get-member
you can see all the methods and properties of an object.
$user.gettype()
return the type of the object you have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With