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

后端 未结 1 1595
说谎
说谎 2021-01-18 06:58

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 -c         


        
1条回答
  •  清歌不尽
    2021-01-18 07:42

    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.

    0 讨论(0)
提交回复
热议问题