How do I escape curly braces {…} in powershell?

蹲街弑〆低调 提交于 2019-12-22 08:26:29

问题


I need to generate multiple lines of xml tag with a GUID in them:

<xmltag_10 value="{ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ}"/>
<xmltag_11 value="{ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ}"/>

and so on

I have this line in a loop where $guid is generated each iteration, and it prints the guid without surrounding braces

Write-Host ('<xmltag_{0} value="{1}"/>' -f $i,$guid)
<xmltag_10 value="ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ"/>

Adding a set of curly braces, I get

Write-Host ('<xmltag_{0} value="{{1}}"/>' -f $i,$guid)
<xmltag_10 value="{1}"/>

How do I escape the outer curly braces? I've tried using `{{1}`} to escape but I get

Error formatting a string: Input string was not in a correct format..

Adding my code for copying and testing:

$i=10
while($i -lt 21)
{
    $guid = ([guid]::NewGuid()).ToString().ToUpper();
    Write-Host ('<xmltag_{0} value="{1}"/>' -f $i,$guid)
    $i++
}

回答1:


To escape curly braces, simply double them:

'{0}, {{1}}, {{{2}}}' -f 'zero', 'one', 'two'
# outputs:
# zero, {1}, {two} 
# i.e. 
# - {0} is replaced by zero because of normal substitution rules 
# - {{1}} is not replaced, as we've escaped/doubled the brackets
# - {2} is replaced by two, but the doubled brackets surrounding {2} 
#   are escaped so are included in the output resulting in {two}

So you could to this:

Write-Host ('<xmltag_{0} value="{{{1}}}"/>' -f $i,$guid)

However; in your scenario you don't need to use -f; it's a poor fit if you need to use literal curly braces. Try this:

$i=10
while($i -lt 21)
{
    $guid = ([guid]::NewGuid()).ToString().ToUpper();
    Write-Host "<xmltag_$i value=`"$guid`"/>"
    $i++
}

This uses regular variable substitution in a double quoted string (but it does require escaping the double quotes using `" (the backtick is the escape character).


Another option would have been to use a format specifier. i.e. Format B causes a GUID to be surrounded by braces. Sadly it also formats the GUID in lowercase, so if the case of the output is part of your requirement, this would not be appropriate.

Write-Host ('<xmltag_{0} value="{1:B}"/>' -f $i, $guid)


来源:https://stackoverflow.com/questions/27257333/how-do-i-escape-curly-braces-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!