Search code examples
windowspowershellescapingquoting

How to escape spaces in a PowerShell one-liner


I want to run an exe with params using powershell one line, like this -

powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList somefile.txt, Run"

And it works, but when I am trying to insert full path with spaces it's crashing

powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList "C:\Program Files\somefile.txt", "Run" "

I tried to use single quote or escape with ` but it's not helping

Maybe someone know what I do wrong?

P.s. running from inside cmd.exe


Solution

  • The easiest solution is to use single-quoting ('...') for the embedded strings:

    powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList 'C:\Program Files\somefile.txt', 'Run'"
    

    Since it is PowerShell that will be interpreting the command string, it recognizes the embedded '...' strings as string literals.


    If you try to embed double-quoted strings ("..."), you face two hurdles:

    • First, PowerShell's CLI requires \ as the escape character for " (whereas internally it is `), so you need to escape the " inside the overall "..." command string as \".

    • Additionally, due to a known problem with Start-Process, you need an extra round of escaping, which makes the solution quite obscure and unwieldy, because you must escape each embedded " as \"`\" (!).

    powershell -ExecutionPolicy Unrestricted "Start-Process -Path program.exe -ArgumentList \"`\"C:\Program Files\somefile.txt\"`\", \"`\"Run\"`\" "