laggingreflex
laggingreflex

Reputation: 34627

Escape "double quotes" inside batch's input parameters

I want to run the following in batch script where it takes an argument (a path)

runas /user:abc "icacls %1 /grant Everyone:(F) /T"

but the argument %1 already contains a " (because it's a path, passed on by context menu's Send To - I don't have much control over this). So when the command runs in batch script it runs like this:

runas /user:abc "icacls "c:\folder" /grant Everyone:(F) /T"

So obviously I need to escape the "s created by %1. How do I perform string manipulation over %1 such that it escaped the quotes?

Upvotes: 25

Views: 60904

Answers (5)

Mike Q
Mike Q

Reputation: 7327

After some quick testing, this is the best method because it :

Upside

  • handles multiple results output from tasklist
  • handles application names with spaces if needed
  • Can easily be changed to case sensitive / insensitive

Downside

  • Calling more than one command which is technically slower

Code

@echo off    
set "EXE=authy desktop.exe"
tasklist /NH /FI "imagename eq %EXE%" | find /i "%EXE%" >nul 2>&1
If %errorlevel% EQU 0 (
    echo %EXE% Is Running
) ELSE (
    echo %EXE% is Not Running
)

Further Consideration

You can change the to && ( ) || ( ) formatting instead of checking errorlevel. Also you can use 'setlocal enabledelayedexpansion' if errorlevel is used more than once by referencing with !errorlevel!.

tasklist /NH /FI "imagename eq %EXE%" | find /i "%EXE%" >nul 2>&1 && (
    echo %EXE% Is Running
) || (
    echo %EXE% is Not Running
)

Upvotes: 0

Andrew Dennison
Andrew Dennison

Reputation: 1089

Each response covers part of the answer. Combining them using backslash & quote: \" you get:

runas /user:abc "icacls \"%~1\" /grant Everyone:(F) /T"

or you can doubled (double) quotes to escape them:

runas /user:abc "icacls ""%~1"" /grant Everyone:(F) /T"

As a side note ^ is occasionally useful for escaping special characters such as <, |, >, ||, &&, and & For example:

echo ^|

but this is pretty rare.

Upvotes: 7

Drarakel
Drarakel

Reputation: 480

A search/replace isn't even needed in such cases. Just strip the original quotes from your argument (with %~1) - then you can add again whatever you want, e.g. the escaped quotes. In your example:

runas /user:abc "icacls \"%~1\" /grant Everyone:(F) /T"

Upvotes: 0

laggingreflex
laggingreflex

Reputation: 34627

SET myPath=%1
SET myPath=%myPath:"=\"%
runas /user:abc "icacls %myPath% /grant Everyone:(F) /T"

Edit - The variable name was changed from path to myPath. PATH is a reserved system variable that should not be used for anything other than what it was intended.

Upvotes: 2

nick
nick

Reputation: 2853

You should be able to use \" Here is a site with a few other escape characters that you might find useful

To perform the string replace:

set temp=%1
set temp=%temp:"=\"%
echo %temp%

Upvotes: 26

Related Questions