bswinnerton
bswinnerton

Reputation: 4721

Getting length of HashTable in 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"]
}

Upvotes: 16

Views: 27946

Answers (3)

CB.
CB.

Reputation: 60918

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

Upvotes: 28

andrux
andrux

Reputation: 2922

That's not an array but a hashtable. Use .count instead:

write-output $user.count

Upvotes: 1

Lee
Lee

Reputation: 144136

$user is a hash table, so you should user$user.count instead.

Upvotes: 4

Related Questions