是否可以通过'copy con'命令创建一个创建另一个批处理文件的批处理文件?

时间:2015-05-30 12:02:53

标签: windows batch-file cmd

行。我的问题几乎解释了自己。是否可以创建批处理文件,执行时会通过copy con命令创建另一个批处理文件? 类似的东西:

@echo off
copy con file.bat
@echo off
echo hallo
exit
^Z
start file.bat

我尝试这样做的唯一问题是你手工制作需要在^ Z之后按Enter键,我找不到任何类型的cmd命令来复制它。 有谁知道这样的事情是否可能?或者批处理文件是否还有其他方法可以重新创建另一个批处理文件或其自身?

谢谢。

3 个答案:

答案 0 :(得分:6)

可能会为^Z发出转义码并使用copy con执行此操作,但为什么会这样做? 只是echo命令的正常重定向。 像这样:

@echo off
echo Generating batch file
echo echo Hello world > hello.bat
echo Now running batch file
echo ----------
call hello.bat
echo ----------
echo Ta-da!

答案 1 :(得分:1)

有多种方法可以从另一个文件中创建批处理文件。使用echo batch code的方法需要转义可能出现在"批处理代码"中的特殊字符。还有其他方法包含来自批处理文件本身的读取行,然后将这些行输出到创建的文件中;在这种情况下,即使行包含特殊字符,这些行也可能具有纯批代码。

您在示例中使用的方法与Unix heredoc功能类似,即:

tr a-z A-Z << END_TEXT
one two three
uno dos tres
END_TEXT

有几种方法可以模拟&#34; Unix heredoc&#34;批量;例如this one

@echo off

rem Definition of heredoc macro
setlocal DisableDelayedExpansion
set LF=^
% Don't remove this line 1/2 %
% Don't remove this line 2/2 %
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
set heredoc=for %%n in (1 2) do if %%n==2 (%\n%
       for /F "tokens=1,2" %%a in ("!argv!") do (%\n%
          if "%%b" equ "" (call :heredoc %%a) else call :heredoc %%a^>%%b%\n%
          endlocal ^& goto %%a%\n%
       )%\n%
    ) else setlocal EnableDelayedExpansion ^& set argv=


rem Heredoc syntax:
rem
rem %%heredoc%% :uniqueLabel [outfile]
rem contents
rem contents
rem ...
rem :uniqueLabel

rem For example:

%heredoc% :endBatch file.bat

@echo off

echo hallo
exit /B

:endBatch

echo Calling created file:
call file.bat
echo Return from created file
goto :EOF


rem Definition of heredoc subroutine

:heredoc label
set "skip="
for /F "delims=:" %%a in ('findstr /N "%1" "%~F0"') do (
   if not defined skip (set skip=%%a) else set /A lines=%%a-skip-1
)
for /F "skip=%skip% delims=" %%a in ('findstr /N "^" "%~F0"') do (
   set "line=%%a"
   echo(!line:*:=!
   set /A lines-=1
   if !lines! == 0 exit /B
)
exit /B

答案 2 :(得分:0)

这样做不是更好吗?也许我不知道你的意思,但我认为这可以帮助你:

@echo off
>newbatch.bat (
echo @echo off
echo echo It works!
echo echo Hope it helped you :)
echo pause >nul
)
run newbatch.bat