views:

1545

answers:

1

I've got a function:

int RunProgram(string exeName, string parameters);

(I'm actually trying to use the ViX API to automate a virtual machine... but I think the following question may apply in other circumstances).

And I'm trying to do this:

RunProgram("c:\\windows\\system32\\cmd.exe",  
"/C \"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > \"C:\\temp\\Folder Containing Spaces\\SomeProgram.out\"");

However, I have problems which are down to the way cmd.exe works. If you read the help for it, it handles " characters in a special way. See the help at the end of question. So, this doesn't execute correctly... I'm guessing cmd.exe strips some quotes which makes the statement ill-formed.

I can do this successfully:

// quotes not required around folder with no spaces
RunProgram("c:\\windows\\system32\\cmd.exe",  
"/C \"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > C:\\temp\\FolderWithNoSpaces\\SomeProgram.out");

But, I really need the first one to work. Is there away around the strange quote processing that cmd.exe uses? I want it to preserve all of the quotes, but there doesn't appear to be an option to make it do that.


If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where the following logic is used to process quote (") characters:

1.  If all of the following conditions are met, then quote characters
    on the command line are preserved:

    - no /S switch
    - exactly two quote characters
    - no special characters between the two quote characters,
      where special is one of: &<>()@^|
    - there are one or more whitespace characters between the
      the two quote characters
    - the string between the two quote characters is the name
      of an executable file.

2.  Otherwise, old behavior is to see if the first character is
    a quote character and if so, strip the leading character and
    remove the last quote character on the command line, preserving
    any text after the last quote character.
+10  A: 

Ah. doh. Think I've answere my own question.

If you use /S, and wrap the whole thing in quotes, it just removes those outer quotes.

cmd.exe /S /C " do what you like here, quotes within the outermost quotes will be preserved "

Scott Langham
+1 The help within `cmd /?` is not as helpful as this answer
Merlyn Morgan-Graham