Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Format operator with string contains "{" and "}"

Context

In PowerShell, you can format a string with -F operator like:

  Get-Content foo.csv | ConvertFrom-Csv -Header Name,Code,Address | `
  ForEach-Object {
    "{0} `n {1} {2}" -F $_.Name,$_.Code,$_.Address
  }

Problem

-F operator returns error like below when the formatted string contains When "{" and "}".

  Get-Content foo.csv | ConvertFrom-Csv -Header Name,Code,Address | `
  ForEach-Object {
    '\addaddress{{0}}{様}{{1}}{{2}}' -F $_.Name,$_.Code,$_.Address
  }
Error formatting a string: Input string was not in a correct format..
At /home/xxxx/foobar.ps1:31 char:5
+     '\addaddress{{0}}{様}{{1}}{{2}}' -F $_.Name,$_.Code,$_.Address
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (\addaddress{0}{様}{1}{2}:String) [], RuntimeException
    + FullyQualifiedErrorId : FormatError

Solution

You should use "{{" and "}}" to output "{" and "}" with format operator, like:

  ForEach-Object {
    '\addaddress{{ {0} }}{{様}}{{ {1} }}{{ {2} }}' -F $_.Name,$_.Code,$_.Address
  }