打开记事本并使用.bat文件写点东西

时间:2018-09-23 10:55:19

标签: windows batch-file exe

使用我想要的批处理文件:

1)打开记事本

2)在记事本中写一些东西并保存

是否可以这样做。你该怎么做?

1 个答案:

答案 0 :(得分:2)

在批处理文件中,使用以下命令使用您选择的文本文件启动Windows记事本,一旦用户退出Windows记事本并将输入的文本保存到文件中,用户就可以输入文本,批处理文件将进一步处理该文本。

@echo off
rem Create a text file with 0 bytes.
type NUL >"%TEMP%\UserText.txt"

rem Start Windows Notepad with that empty text file and halt
rem execution of batch file until user finished typing the
rem text and exiting Notepad with saving the text file.
%SystemRoot%\notepad.exe "%TEMP%\UserText.txt"

rem Delete the text file if its file size is still 0.
for %%I in ("%TEMP%\UserText.txt") do if %%~zI == 0 del "%TEMP%\UserText.txt" & goto :EOF

rem Do something with the text file like printing the text.
type "%TEMP%\UserText.txt"

rem Finally delete the text file no longer needed.
del "%TEMP%\UserText.txt"
pause

但是,如果批处理文件应该自己创建一个文本文件,则完全不需要使用Windows记事本,如以下代码所示:

@echo off
(
echo This is a demo on how text can be written into a text file.
echo/
echo The command ECHO is used to output text to console which is redirected
echo with redirection operator ^> into a file which is created always new
echo with overwriting the text file if already existing by chance.
echo/
echo See the Microsoft article "Using command redirection operators" with URL
echo https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490982(v=technet.10^)
echo for details.
) >"%TEMP%\UserText.txt"

rem Do something with the text file like printing the text.
type "%TEMP%\UserText.txt"

rem Finally delete the text file no longer needed.
del "%TEMP%\UserText.txt"
pause

注意:在Windows命令处理器处理 ECHO 命令行时,某些字符必须用脱字符号^进行转义,才能解释为文字字符。重定向操作符<>|&必须使用^)进行转义,如果命令行位于以(开头并以匹配的)结尾的命令块中,则是不用^进行转义且没有写在双引号参数字符串内的右圆括号。

批处理文件中的百分号%必须转义一个百分号,才能解释为文字字符,而不是批处理文件参数引用的开头,循环变量的引用或begin /结束环境变量引用。此外,如果启用了延迟的环境变量扩展,则必须用两个插入号转义感叹号!,即使用^^,这不是默认情况。

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。

  • call /?
  • del /?
  • echo /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • rem /?
  • set /?
  • type /?

另请参阅How does the Windows Command Interpreter (CMD.EXE) parse scripts?