llevera
llevera

Reputation: 239

Formatting a Powershell string containing hashtable values

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:

$hash = @{face='Off';}

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

This works:

Write-Host Face $hash['face']
=> Face Off

However, this doesn't:

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:

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:

$hashvalue = $hash['face']
write-host Face/$hashvalue
=> Face/Off

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

Upvotes: 7

Views: 7256

Answers (4)

mjolinor
mjolinor

Reputation: 68263

Another option is to insert your slash with the -Separator option of Write-Host:

$hash = @{Face="off"}
Write-Host ("Face",$hash.Face) -Separator '/'

Upvotes: 0

Andy Arismendi
Andy Arismendi

Reputation: 52577

In addition to using sub expressions as Joey showed you can:

Use string formatting:

Write-Host ('Face/{0}' -f $hash.face)

This will stick the value of face key in the place of {0}

Use string concatenation:

Write-Host ('Face/' + $hash.face)

Both of those require an expression to be evaluated which outputs a string which is used as Write-Host's Object parameter.

Upvotes: 1

manojlds
manojlds

Reputation: 301137

In such cases, and more so if there are more variables involved, I prefer using the string formatting. While in this case you can live with the $(..), be aware that string formatting will remove lot of doubt, cruft and improves readability:

write-host ("Face/{0}" -f $hash['face'])

Upvotes: 3

Joey
Joey

Reputation: 354476

Sure, use a subexpression:

Write-Host Face/$($hash['face'])

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

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.

Upvotes: 11

Related Questions