Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++
}
like image 377
orderof1 Avatar asked Dec 02 '14 19:12

orderof1


People also ask

How do you escape brackets in PowerShell?

The PowerShell escape character is the backtick "`" character. This applies whether you are running PowerShell statements interactively, or running PowerShell scripts.

How do you remove curly braces from string?

String n = s. replaceAll("/{", " "); String n = s. replaceAll("'{'", " ");

What do curly brackets do in PowerShell?

Curly braces in PowerShell variable names allow for arbitrary characters in the name of the variable. If there are no "pathological" characters in the variable name, then the braces are not needed and have no effect.


1 Answers

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)
like image 66
briantist Avatar answered Oct 04 '22 06:10

briantist