Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use nested quotes when calling a powershell script within a batch file?

I have a DOS batch file that has a line that executes a powershell script. First I tried a very simple script with this line in the batch file:

powershell -command "get-date" < nul

That worked great. But the script has nested double-quote characters, which can sometimes be escaped with a backtick (`) character. So then I tried this:

powershell -command "Write-Host `"hello world`"" < nul

That also worked great. However, the script I need to run is pretty complicated and has more than one level of nested double-quote characters. I have taken the complicated script and simplified it to an example that has the same principles here:

[string]$Source =  "    `"hello world`" ";
Write-Host $Source;

If I save this script inside a PS script file and run it, it works fine, printing out “hello world” including the double quotes, but I need to embed it in the line in the batch file. So I take the script and put it all on one line, and try to insert it into the batch file line, but it doesn’t work. I try to escape the double-quotes, but it still doesn’t work, like this:

powershell -command "[string]$Source =  `"    `"hello world`" `";Write-Host $Source;" < nul

Is there a way to do what I want? You might ask why I am doing this, but it’s a long story, so I won’t go into the details. thanks

like image 869
John Gilmer Avatar asked Mar 05 '14 12:03

John Gilmer


1 Answers

You'll have to use a combination of batch's escape character and PowerShell's escape character.

In batch, when escaping quotes, you use the common shell backslash (\) to escape those quotes. In Powershell, you use the backtick `.

So if you wanted to use batch to print out a quoted string with Powershell, you need to first batch escape the quote to declare the variable in Powershell, then to ensure the string is quoted you need batch and Powershell escape another quote, and then your add your desired string, ensuring you batch escape first.

For your example, this will work:

powershell -command "[string]$Source =  \"`\"hello world`\"\"; Write-Host $Source;"

Here's a break down of the declaration of the $Source variable:

"[string]$Source = # open quote to begin -command parameter declaration
\"          # batch escape to begin the string portion
`\"         # Powershell+Batch escape
hello world # Your content
`\"         # Posh+Batch again
\";         # Close out the batch and continue
more commands " # Close quote on -command parameter 

This renders the string like this in batch:

`"hello world`"

One note, you don't need to explicitly cast $Source as a string since you are building it as a literal string from scratch.

$Source = "string stuff" will work as intended.

like image 89
SomeShinyObject Avatar answered Oct 01 '22 17:10

SomeShinyObject