How to avoid curly braces {...} in powershell?

I need to generate multiple lines of XML tag with GUIDs in them:

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

      

etc

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

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

      

By 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 tried to escape with '{{1}'}, but I got

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

      

Adding my code to copy and test:

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

      

+4


source to share


1 answer


To avoid the curly braces, just 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 can to this:

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

      


However, in your scenario, you don't need to use -f

; This is not good if you need to use literal curly braces. Try it:



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

      

This uses the usual substitution of variables in a double-quoted string (but this requires escaping double quotes with '"(the backward character is an escape character).


Another option is to use the format specifier . the format B

forces the GUID to be enclosed in curly braces. Unfortunately, it also formats GUIDs in lower case, so if the output case is part of your requirement, it won't be appropriate.

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

      

+7


source







All Articles