Batch cmd won't accept redirect symbol

Viewed 106

I have a batch script that's running a command that should forward the result to a file:

start cmd /k "tasklist | find ^"Notepad^" ^> ^"C:\Users\Improvise\Desktop\notepadDeets.txt^""

The following works in the cmd prompt:

tasklist | find "Notepad" > "C:\Users\Improvise\Desktop\notepadDeets.txt"

In this script, the command will work like so:

start cmd /k "tasklist | find ^"Notepad^""

But when I try to add the > "C:\Users\Improvise\Desktop\notepadDeets.txt".

With ^> the error msg is:

Access denied - >

With > the error msg is:

FIND: Parameter format not correct

Am I not escaping this character correctly? Why does it not work in the batch script, and how can I get it to work?

1 Answers

You do not need to escape special characters inside the outer quotes. From cmd /?:

[...] 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 [...]

The following will work:

start cmd /k "tasklist | find /I "Notepad" >"C:\Users\Improvise\Desktop\notepadDeets.txt""

Or, without all-enclosing quotes, and with the special characters escaped:

start cmd /k tasklist ^| find /I "Notepad" ^>"C:\Users\Improvise\Desktop\notepadDeets.txt"

[ EDIT ]   The following explains the errors quoted in the original post.

With ^> the error msg is:

Access denied - >

With ^> the unescaped > is passed to the find command, which interprets it as a filename to search. That fails because > is an illegal filename, and is reported as an "access denied" error for some reason. Variations of the same error can be duplicated at the command prompt:

C:\etc>find "notepad" ^>
Access denied - >

C:\etc>find "notepad" ^> nul
Access denied - >
File not found - NUL

C:\etc>find "notepad" ^>nul
File not found - >NUL

With > the error msg is:

FIND: Parameter format not correct

With an unescaped > the redirection applies to the top level start command, so what gets executed is cmd /k "tasklist | find ^"Notepad", which in the end runs find ^"Notepad causing the "parameter format not correct" error:

C:\etc>find ^"Notepad
FIND: Parameter format not correct
Related