How do I escape curly braces {...} in powershell?
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)
Related videos on Youtube
Comments
-
orderof1 about 1 year
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++ }
-
orderof1 almost 9 yearsThanks! This works. Just had to add a curly brace inside. Will accept once Stackoverflow minimum timer for accepting answers allows me.
-
EBGreen almost 9 yearsWhile -f is not required, just for future reference if you do need it: Write-Host ('xmltag_{0} value="{{{1}}}"/>' -f $i,$guid)
-
ekkis about 8 yearsthanks @EBGreen. I would have picked yours as the better answer