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

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=10while($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)