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.

1
  • 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") Commented May 18, 2015 at 2:30

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your explanation! This extra $ solves my problem(interpretation)!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.