1

In PowerShell, why does this return nothing:

PS > $y = "$prid?api"
PS > echo $y

But these work better:

PS > $y = "$prid\?api"
PS > echo $y
18\?api
PS > $y = "${prid}?api"
PS > echo $y
18?api
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • 3
    Check out this post [PowerShell string interpolation syntax](https://stackoverflow.com/questions/60323111/powershell-string-interpolation-syntax) – Daniel Feb 05 '21 at 23:30
  • In case you're interested: I've added info regarding the v7.1+ _null-conditional_ operator, (`?.` and `?[...]`), which clashes with the permissiveness of allowing use of `?` as part of a variable name without `{...}`. – mklement0 Feb 06 '21 at 00:02

1 Answers1

5

Surprisingly, ? can be used in a PowerShell variable name without requiring that the name be enclosed in {...}.

Therefore, based on the rules of PowerShell's expandable strings (string interpolation inside "..." strings), "$prid?api" looks for a variable with verbatim name prid?api rather than considering the ? to implicitly terminate the preceding identifier.

That is, you can actually define and reference a variable named prid?api as follows:

PS> $prid?api = 'hi'; $prid?api
hi

This surprising permissiveness actually gets in the way of a recently introduced language feature, null-conditional access, introduced in PowerShell (Core) 7.1:

# v7.1+; note that the {...} around the name is - unexpectedly - *required*.
${variableThatMayBeNull}?.Foo()

GitHub issue #14025 advocates for obviating the need to use {...} in this case.

mklement0
  • 382,024
  • 64
  • 607
  • 775