Formatting a Powershell String Containing Hash Table Values

The answer to this is likely to be trivial, but I spent half an hour and still can not solve it.

Suppose I have the following hash table:

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

What I tried to do displays the value "face" along some other string elements.

It works:

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

However, it is not:

 Write-Host Face/$hash['face'] => Face/System.Collections.Hashtable[face] 

Somehow, the absence of a space affected the operator’s priority - now it evaluates the $ hash as a string, then the [face] concatenation.

Trying to solve this problem, I tried:

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

Now I have extra space that I don’t want. This works, but I don’t want the extra line to just re-start:

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

Any idea how to make this work as a single line?

+6
source share
4 answers

Of course, use a subexpression:

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

Typically, I just use a string if I need precise control over the space using Write-Host:

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

Yes, in this case you need to express again, but more, because you simply cannot include an expression like $foo['bar'] in a string otherwise :-)

By the way, $hash.face works just as well, with much less visible interference.

+9
source

In such cases, and moreover, if there are more variables, I prefer to use string formatting. Remember that in this case you can live with $(..) , keep in mind that formatting strings eliminates many doubts, distorts and improves readability:

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

In addition to using the subsamples shown by Joey, you can:

Use string formatting:

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

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

Use string concatenation:

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

Both of them require an expression for evaluation, which displays a string that is used as the Write-Host Object parameter.

+1
source

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

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

Source: https://habr.com/ru/post/909854/


All Articles