Weird behavior in nested expression

Welcome Forums General PowerShell Q&A Weird behavior in nested expression

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
1 year, 7 months ago.

  • Author
    Posts
  • #65355

    Participant
    Points: 0
    Rank: Member

    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
    Ron

    Participant
    Points: 0
    Rank: Member

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

    >"abd""def"
    abd"def
    >$('""')
    ""
    >"$('""')"
    "
    • #65839

      Participant
      Points: 0
      Rank: Member

      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
      Ron

      Participant
      Points: 0
      Rank: Member

      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

    Participant
    Points: 30
    Rank: Member

    I like to use a string format:

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

The topic ‘Weird behavior in nested expression’ is closed to new replies.