1

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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Ravi.
  • 674
  • 2
  • 9
  • 21

1 Answers1

2

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Thanks. I tried to run both commands and it still fails with `The system cannot find the file specified` – Ravi. Mar 26 '21 at 06:12
  • 3
    The last sample can't work, because `setlocal enabledelayedexpansion` doesn't work in command line context. The second sample needs some quotes around the `set` commands (I already edited the answer for that) – jeb Mar 26 '21 at 06:49
  • I don't have an option of calling a batch script in my solution so I'm unfortunately stuck with one-liners call. That said, the updated command works but ONLY when I call it inside a command prompt. If I go to run box and type the command or call it from my program then I'm getting the same error `The system cannot find the file specified` any idea why? – Ravi. Mar 26 '21 at 07:04
  • Ignore my last comment, not sure why cmd is behaving it this way, when I ran the same command on a different VM it worked, then I restarted my machine and ran the same command again and sure enough, it works. – Ravi. Mar 26 '21 at 07:10