Weird behavior in nested expression

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


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"')"

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.

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


What “rule for escaping double quotes”?

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

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

PS C:\> """"

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.

I like to use a string format:

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