[英]Command Prompt: Execute Commands from Any Text File (Not Having “.bat” or “.cmd” Extensions)
I can't find any way to do, for example, the following: 我找不到任何方法,例如,以下内容:
cmd.exe /C "script.txt"
In other words, I need Command Prompt to (try) to execute file with any extension (not necessarily .bat
or .cmd
) if it contains valid batch script code. 换句话说,如果它包含有效的批处理脚本代码,我需要命令提示符(尝试)执行任何扩展名(不一定是.bat
或.cmd
)的文件。 I'm looking for behavior similar to Unix shells: 我正在寻找类似于Unix shell的行为:
./script.txt
While on Unix the shebang ( #!/bin/sh
) is responsible for understanding that the file is actually a script, it seems like on Windows .bat
or .cmd
extensions play the same role, indicating a batch script file for Command Prompt. 在Unix上, shebang ( #!/bin/sh
)负责理解该文件实际上是一个脚本,似乎在Windows .bat
或.cmd
扩展名中扮演相同的角色,表示命令提示符的批处理脚本文件。
Is it possible to avoid that and force Command Prompt to interpret a file with any name? 是否可以避免这种情况并强制命令提示符解释具有任何名称的文件?
NOTE: Please, no answers like: 注意:请不要回答:
Give your file
.bat
or.cmd
extension. 提供文件.bat
或.cmd
扩展名。
That's not what the question is about. 这不是问题所在。
This depends on the complexity of the NON-Batch file. 这取决于NON-Batch文件的复杂性。 If the NON-Batch file does not use these facilities: 如果NON-Batch文件不使用这些功能:
then you may execute any file as a "Batch file" via this trick: 然后你可以通过这个技巧执行任何文件作为“批处理文件”:
cmd < anyFile.ext
you first need an "installation" script : 你首先需要一个“安装”脚本:
@echo off
rem :: A files with .TEST extension will be able to execute batch code but is not perfect as the %0 argument is lost
rem :: "installing" a caller.
if not exist "c:\caller.bat" (
echo @echo off
echo copy "%%~nx1" "%%temp%%\%%~nx1.bat" /Y ^>nul
echo "%%temp%%\%%~nx1.bat" %%*
) > c:\caller.bat
rem :: associating file extension
assoc .test=batps
ftype batps=c:\caller "%%1" %*
then try a simple .test
file: 然后尝试一个简单的.test
文件:
@echo off
for /l (1;1;10) do (
echo testing .TEST extension
)
In fact ASSOC
and FTYPE
both have immediate effect so you can start a .test
file right after "installation". 实际上ASSOC
和FTYPE
都会立即生效,因此您可以在“安装”之后立即启动.test
文件。 With direct editing of the registry eventually you can get more control -> How to create file extension that behaves as .cmd/.bat? 通过直接编辑注册表,您最终可以获得更多控制权 - > 如何创建行为为.cmd / .bat的文件扩展名? . 。 Check also drop handlers -> http://msdn.microsoft.com/en-us/library/windows/desktop/cc144165%28v=vs.85%29.aspx 检查还删除处理程序 - > http://msdn.microsoft.com/en-us/library/windows/desktop/cc144165%28v=vs.85%29.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.