Search code examples
batch-filecmdrunas

Runas CMD is not working because of quoting


I'm using this line in a batch file:

Runas /user:domain\user "cmd /C echo Test > C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config"

The problem ist, this is only working if the path of the file has no blank spaces. And I can not put the path in quotation marks as usually because the whole CMD-command has to be in quotation marks.

Runas /user:domain\user "cmd /C echo Test > "C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config""

Even escaping the double quotation marks is not working.

Runas /user:domain\user "cmd /C echo Test > ""C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config"""

Does anybody have an idea how to deal with that problem? Thanks!


Solution

  • Escape inner double quotes using \ Reverse Solidus (backslash) as follows:

    Runas /user:domain\user "cmd /C echo Test>\"C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config\""
    

    Resources (equivalent):

    Example use case:

    d:\bat> runas /noprofile /user:user "cmd /V:ON /C whoami&echo \"!CD!\"&echo !CD! Test runas>>\"%CD%\test runas.txt\"&pause"
    Enter the password for user:
    Attempting to start cmd /V:ON /C whoami&echo "!CD!"&echo !CD! Test runas>>"d:\bat\test runas.txt"&pause as user "MY-PC\user" ...
    
    d:\bat> type "test runas.txt"
    C:\WINDOWS\system32 Test runas
    C:\WINDOWS\system32 Test runas