要转义大括号,只需将它们加倍即可:
'{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}
所以你可以这样做:
Write-Host ('<xmltag_{0} value="{{{1}}}"/>' -f $i,$guid)
However;在你的场景中你不需要使用-f
;如果您需要使用字面大括号,那么它不太合适。尝试这个:
$i=10
while($i -lt 21)
{
$guid = ([guid]::NewGuid()).ToString().ToUpper();
Write-Host "<xmltag_$i value=`"$guid`"/>"
$i++
}
这在双引号字符串中使用常规变量替换(但它确实需要使用“”转义双引号(反引号是转义字符)。
另一种选择是使用格式说明符 https://learn.microsoft.com/en-us/dotnet/api/system.guid.tostring#System_Guid_ToString_System_String_。即格式B
导致 GUID 被大括号括起来。遗憾的是,它还将 GUID 格式化为小写,因此如果输出的大小写是您的要求的一部分,那么这将是不合适的。
Write-Host ('<xmltag_{0} value="{1:B}"/>' -f $i, $guid)