Weird behavior in nested expression

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 2 months, 2 weeks ago.

  • Author
    Posts
  • #65355
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    I'm not sure if "nested expression" is the right term, but I'm referring to expression evaluation in a double quoted string.

    Ref. https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_quoting_rules

    Also, in a double-quoted string, expressions are evaluated, and the result is inserted in the string. For example:
    "The value of $(2+3) is 5."

    Weird behavior:

    PS C:\> "$('"')"
    "
    
    PS C:\> "$('""')"
    "
    
    PS C:\> "$('"x"')"
    "x"
    

    In the first example the expression is a string with the double quote character. This is fine.

    In the second example the string should have been two double quote characters, but a single double quote is returned.

    In the third example you can see that both double quotes are returned if you put something in between them.

    Why doesn't the second example return two double quotes as expected? Or you might expect an error due to nested quotation, but then you would expect some kind of parser error.

  • #65362
    Profile photo of Ron
    Ron
    Participant

    The rule for escaping double quotes is taking precedence over evaluation when placed inside of double quotes.

    >"abd""def"
    abd"def
    >$('""')
    ""
    >"$('""')"
    "
    • #65839
      Profile photo of Paal Braathen
      Paal Braathen
      Participant

      What "rule for escaping double quotes"?

      https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_escape_characters

      In Windows PowerShell, the escape character is the backtick (`)

      This should, the way I see things, produce a parsererror:

      PS C:\> """"
      "
    • #65847
      Profile photo of Ron
      Ron
      Participant

      It might seem more obvious to me coming from (Visual) Basic in its many flavors. But, when you need to embed double quotes inside of double quotes, you double the double quotes. This also applies in CSV files as well as a number of other places where strings are specified by using double quotes.

      "You have to double your ""double quotes""."
      You have to double your "double quotes".

      Powershell gives you more options for working with double and single quotes in strings, including expression evaluation, which can also make it more confusing.

  • #65853
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    I like to use a string format:

    $knollType = "grassy"
    'It was the, "man on the {0} knoll".' -f $knollType
    

You must be logged in to reply to this topic.