16

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"]
}
Ben English
  • 3,900
  • 2
  • 22
  • 32
bswinnerton
  • 4,533
  • 8
  • 41
  • 56

3 Answers3

27

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

Umar Farooq Khawaja
  • 3,925
  • 1
  • 31
  • 52
CB.
  • 58,865
  • 9
  • 159
  • 159
  • +1 For pointing out get-member. Somehow I never learned this and it will make things much easier in the future. – Logan Feb 10 '17 at 23:14
4

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

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Though note that (painfully) [everything has a `Length` an `Count` now](https://stackoverflow.com/a/29761715/1028230). Explanation at [that link](https://stackoverflow.com/a/29761715/1028230). – ruffin Nov 30 '21 at 17:50
1

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

write-output $user.count
andrux
  • 2,782
  • 3
  • 22
  • 31