简体   繁体   English

cmd.exe /C 无法运行命令

[英]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.我通过将标志从 /C 更改为 /K 来发现错误。

Any idea what is wrong with this command?知道这个命令有什么问题吗?

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.你不能这样做SET filename=testfile_26032021.txt && SET newfilename=%filename:~9,8%因为%filename%在解析时扩展它还不可用。 You must enable delayed expansion and tell cmd to expand the command later with !variable_name!您必须启用延迟扩展并告诉 cmd 稍后使用!variable_name! . . Besides && ends the previous command so your whole thing is parsed as 3 commands:除了&&结束前一个命令,所以你的整个事情被解析为 3 个命令:

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也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM