Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting length of HashTable in powershell

Tags:

powershell

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"]
}
like image 897
bswinnerton Avatar asked Nov 09 '12 16:11

bswinnerton


People also ask

How to create hashtable in PowerShell?

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.

How to add key/value pairs to a hashtable in PowerShell?

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}}

How to convert a string to a hash table in PowerShell?

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:

How do you get multiple values from a hashtable?

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.


1 Answers

@{} 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.

like image 62
CB. Avatar answered Sep 21 '22 05:09

CB.