3

It's quite weird that Write-Host doesn't seem to parse variable's property.

PS C:\Users\x> $v=@{item1="kkk";item2="aaa"}
PS C:\Users\x> $v.Keys|%{$v.Item($_)}
kkk
aaa
PS C:\Users\x> Write-Host "$v.Count elements"
System.Collections.Hashtable.Count elements
PS C:\Users\x> $v.Count
2
PS C:\Users\x> $v
Name                           Value
----                           -----
item1                          kkk
item2                          aaa

You could see, $v is a hashtable and

$v.Count

prints 2. But why does

Write-Host "$v.Count"

print out System.Collections.Hashtable.Count? This is not what I expected.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Immanuel Kant
  • 517
  • 3
  • 8
  • I don't have a solid answer for why it does it, but it's a behavior that I've noticed a lot - you can include a simple variable in a string, but not members with dot notation. If you want to have that work, you have to put it in a single variable first (```$count = $v.count```), use string formatting (```Write-Host ("{0} elements" -f $v.Count)```) or provide it as separate elements (```Write-Host $v.Count "elements"```) – squid808 May 18 '15 at 02:30

1 Answers1

6

Text representation of $v is System.Collections.Hashtable ([string]$v or "$v"). And "$v.Count elements" means {text representation of $v}.Count elements not {text representation of $v.Count} elements, so for me it is expected that you get System.Collections.Hashtable.Count elements as result.

Write-Host is not responsible for expanding double quoted strings. It done by PowerShell before it invoke Write-Host.

"$v.Count" 

prints 2

For me it prints System.Collections.Hashtable.Count. 2 printed by $v.Count not by "$v.Count".

You should use "$($v.Count) elements" to get expected result.

user4003407
  • 21,204
  • 4
  • 50
  • 60