Format the PowerShell string containing the hash table value
The answer may be simple, but it took me half an hour to solve the problem
Suppose I have the following hash table: @ h_ 301_ 3@
$hash = @{face='Off';}
What I'm trying to do is output the value of "face" along some other string elements@ H_ 301_ 3@
This is valid: @ h_ 301_ 3@
Write-Host Face $hash['face'] => Face Off
But this is not: @ h_ 301_ 3@
Write-Host Face/$hash['face'] => Face/System.Collections.Hashtable[face]
Somehow, the lack of space has affected the priority of the operator - now it is evaluating $hash as a string, followed by the connection [face]@ H_ 301_ 3@
Trying to solve this priority problem, I tried: @ h_ 301_ 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 additional rows reassigned: @ h_ 301_ 3@
$hashvalue = $hash['face'] write-host Face/$hashvalue => Face/Off
Do you know how to make it work as a single line@ H_ 301_ 3@
Solution
Of course, use a subexpression:
Write-Host Face/$($hash['face'])
Usually, if I need to use write host to precisely control whitespace, I only use one string: @ H_ 301_ 3@
Write-Host "Face/$($hash['face'])"
Yes, in this case, you need to use the subexpression again, but more because you can't include expressions such as $foo ['bar'] in the string; -)@ H_ 301_ 3@
By the way, $hash Face works the same way for visual confusion@ H_ 301_ 3@