2

In PowerShell I want to provide a single command line argument which contains literal quotes plus a PowerShell variable value.

I am aware of this question and its answers, but it doesn't seem to provide a way to enable string interpolation while also having literal quotes unstripped.

A synthetic example:

I want to execute this line of ruby code from the command line: puts "'u'=<my-user-provided-from-the-shell>". (Reminder that this is a synthetic example. I know I can get the username in ruby. I know I can change the code so it doesn't actually need double quotes. For this example I want to execute this exact line of code)

In cmd, I would do this:

> ruby -e "puts \"'u'=%USERNAME%\""

And it works as expected.

Can I somehow send the exact same argument from powershell?

> ruby -e "puts \"`'u`'=$env:USERNAME\""

Doesn't work. It fails and produces invalid ruby code. The first quote makes it in, but the \ from the second goes inside

> ruby -e 'puts \"''u''=$env:USERNAME\"'

Doesn't fail, but $env:USERNAME is not expanded.

Is it even possible to pass both literal double quotes and a variable value in a single command-line arg?

Borislav Stanimirov
  • 1,609
  • 12
  • 23

1 Answers1

2

Thanks to Abra who posted this link I was able to come up with a solution which works using the subexpression operator:

> ruby -e "puts $('\"')'u'=$env:USERNAME$('\"')"

Using $('\"') looks like the definitive answer to such problems. I don't know why it's not posted in other related questions.

Borislav Stanimirov
  • 1,609
  • 12
  • 23