Question:
The answer to this is likely to be trivial, but I have spent half an hour and still can’t work it out.
Assume I have a the following hashtable:
1 2 |
$hash = @{face='Off';} |
What I have tried to do, is output the value of “face” along side some other string elements.
This works:
1 2 3 |
Write-Host Face $hash['face'] => Face Off |
However, this doesn’t:
1 2 3 |
Write-Host Face/$hash['face'] => Face/System.Collections.Hashtable[face] |
Somehow the lack of a space has affected the operator precedence – it is now evaluating $hash as a string, the concatenating [face] afterwards.
Trying to solve this precedence problem, I tried:
1 2 3 |
Write-Host Face/($hash['face']) => Face/ Off |
I now have an extra space I don’t want.
This works, but I don’t want the extra line just to reassign:
1 2 3 4 |
$hashvalue = $hash['face'] write-host Face/$hashvalue => Face/Off |
Any idea how to get this working as a one-liner?
Answer:
Sure, use a subexpression:
1 2 |
Write-Host Face/$($hash['face']) |
Generally, I’d just use a string, if I need precise control over whitespace with Write-Host:
1 2 |
Write-Host "Face/$($hash['face'])" |
Yes, in this case you need a subexpression again, but more because you simply can’t include an expression like $foo['bar']
in a string otherwise 😉
By the way, $hash.face
works just as well with much less visual clutter.