Search code examples
windowsbatch-filecmdcommand-line

cmd.exe /C unable to run the command


I'm running below command which is working successfully if I run it manually via command prompt

SET filename=testfile_26032021.txt && SET newfilename=%filename:~9,8% && copy C:\test\updatedtestfile_%newfilename%.txt C:\test\updatedtestfile_%newfilename%.txt.temp

But when I run this through an external call I get an error

The system cannot find the file specified.

Here's the command I'm running

cmd.exe /C SET filename=testfile_26032021.txt && SET newfilename=%filename:~9,8% && copy C:\test\updatedtestfile_%newfilename%.txt C:\test\updatedtestfile_%newfilename%.txt.temp

I caught the error by changing the flag from /C to /K.

Any idea what is wrong with this command?


Solution

  • You can't do like this SET filename=testfile_26032021.txt && SET newfilename=%filename:~9,8% because %filename% is expanded at parsing time where it's not available yet. You must enable delayed expansion and tell cmd to expand the command later with !variable_name!. Besides && ends the previous command so your whole thing is parsed as 3 commands:

    cmd.exe /C SET filename=testfile_26032021.txt
    SET newfilename=%filename:~9,8%
    copy C:\test\updatedtestfile_%newfilename%.txt C:\test\updatedtestfile_%newfilename%.txt.temp
    

    So you must quote the command like this

    cmd.exe /V:on /C "SET "filename=testfile_26032021.txt" && SET "newfilename=!filename:~9,8!" && copy C:\test\updatedtestfile_!newfilename!.txt C:\test\updatedtestfile_!newfilename!.txt.temp"
    

    or

    cmd.exe /C "setlocal enabledelayedexpansion && SET filename=testfile_26032021.txt && SET newfilename=!filename:~9,8! && copy C:\test\updatedtestfile_!newfilename!.txt C:\test\updatedtestfile_!newfilename!.txt.temp"
    

    See also