Command Prompt: Execute Commands from Any Text Fil

2019-01-15 21:30发布

问题:

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. I'm looking for behavior similar to Unix shells:

./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.

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.

That's not what the question is about.

回答1:

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:

@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". With direct editing of the registry eventually you can get more control -> How to create file extension that behaves as .cmd/.bat? . Check also drop handlers -> http://msdn.microsoft.com/en-us/library/windows/desktop/cc144165%28v=vs.85%29.aspx



回答2:

This depends on the complexity of the NON-Batch file. If the NON-Batch file does not use these facilities:

  • Access to Batch file parameters via %1 %2 ... and execution of SHIFT command.
  • Execution of GOTO command.
  • Execution of CALL :NAME command (internal subroutine).
  • Execution of SETLOCAL/ENDLOCAL commands.

then you may execute any file as a "Batch file" via this trick:

cmd < anyFile.ext

Further details at this post