Search code examples
powershellbatch-fileescapingquotesdouble-quotes

Correct Way To Escape Quotes In PowerShell Command Run From Command Line?


I have the following command that I need to run from a batch file:

PowerShell -Command "Start-Process cmd -ArgumentList '/C "MKLINK /D "C:\Folder With Spaces\Another Folder" "%UserProfile%\Documents\Folder With Spaces""' -Verb RunAs"

however when this command is actually executed the quotes around the two folders with spaces in them is completely ignored and the command fails to run correctly. What would be the correct approach to escape the various quotes involved in this statement? I've tried using ` and ^ in front of the quotes surrounding the folder names but neither worked.


Solution

    • For powershell.exe, the Windows PowerShell CLI, to use " characters passed to the -Command parameter as part of the PowerShell code to execute, they must be escaped, in the simplest form as \".

    • Due to cmd.exe's parsing quirks, " characters embedded inside a cmd /c "..." call do not require additional escaping.

    Therefore:

    PowerShell -Command "Start-Process cmd -ArgumentList '/C \"MKLINK /D \"C:\Folder With Spaces\Another Folder\" \"%UserProfile%\Documents\Folder With Spaces\"\"' -Verb RunAs"