Formatting a Powershell string containing hashtable values

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:

What I have tried to do, is output the value of “face” along side some other string elements.

This works:

However, this doesn’t:

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:

I now have an extra space I don’t want.
This works, but I don’t want the extra line just to reassign:

Any idea how to get this working as a one-liner?

Answer:

Sure, use a subexpression:

Generally, I’d just use a string, if I need precise control over whitespace with Write-Host:

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.

Source:

Formatting a Powershell string containing hashtable values by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply