windows 从批处理文件中重定向输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20484151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirecting Output from within Batch file
提问by user3085030
I am creating a batch file with some simple commands to gather information from a system. The batch file contains commands to get the time, IP information, users, etc.
我正在使用一些简单的命令创建一个批处理文件来从系统收集信息。批处理文件包含获取时间、IP 信息、用户等的命令。
I assembled all the commands in a batch file, and it runs, but I would like the batch file, when run to output the results to a text file (log). Is there a command that I can add to the batch that would do so?
我在一个批处理文件中组装了所有命令,它运行,但我想要批处理文件,当运行时将结果输出到文本文件(日志)。是否有可以添加到批处理中的命令?
Keep in mind I do not want to run the batch from cmd, then redirect output ; I want to redirect the output from inside the batch, if that is possible.
请记住,我不想从 cmd 运行批处理,然后重定向输出;如果可能的话,我想从批处理内部重定向输出。
回答by dbenham
The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.
简单天真的方法很慢,因为它多次打开并将文件指针定位到文件结尾。
@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt
A better way - easier to write, and faster because the file is opened and positioned only once.
更好的方法 - 更容易编写,速度更快,因为文件只打开和定位一次。
@echo off
>output.txt (
command1
command2
...
commandN
)
Another good and fast way that only opens and positions the file once
仅打开和定位文件一次的另一种好而快速的方法
@echo off
call :sub >output.txt
exit /b
:sub
command1
command2
...
commandN
Edit 2020-04-17
编辑 2020-04-17
Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the &
notation to reference the already opened files.
您可能时不时地想要重复写入两个或多个文件。您可能还希望在屏幕上显示不同的消息。仍然可以通过重定向到带括号的块或子例程之外的未定义句柄来有效地执行此操作,然后使用该&
符号引用已打开的文件。
call :sub 9>File1.txt 8>File2.txt
exit /b
:sub
echo Screen message 1
>&9 File 1 message 1
>&8 File 2 message 1
echo Screen message 2
>&9 File 1 message 2
>&8 File 2 message 2
exit /b
I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flawwhen performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.
我选择以相反的顺序使用句柄 9 和 8,因为在对同一命令执行多个重定向时,由于Microsoft 重定向实现设计缺陷,这种方式更有可能避免潜在的永久重定向。这是极不可能的,但如果您足够努力,即使这种方法也可能暴露错误。如果您进行重定向,则可以保证避免该问题。
3>File1.txt ( 4>File2.txt call :sub)
exit /b
:sub
etc.
回答by Kalpesh Soni
if you want both out and err streams redirected
如果您想要重定向 out 和 err 流
dir >> a.txt 2>&1
回答by Anthony
I know this is an older post, but someone will stumble across it in a Google search and it also looks like some questions the OP asked in comments weren't specifically addressed. Also, please go easy on me since this is my first answer posted on SO. :)
我知道这是一篇较旧的帖子,但有人会在谷歌搜索中偶然发现它,而且看起来 OP 在评论中提出的一些问题没有得到具体解决。另外,请放轻松,因为这是我在 SO 上发布的第一个答案。:)
To redirect the output to a file using a dynamically generated file name, my go-to (read: quick & dirty) approach is the second solution offered by @dbenham. So for example, this:
要使用动态生成的文件名将输出重定向到文件,我的首选(阅读:快速和脏)方法是@dbenham 提供的第二个解决方案。例如,这个:
@echo off
> filename_prefix-%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log (
echo Your Name Here
echo Beginning Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
REM do some stuff here
echo Your Name Here
echo Ending Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
)
Will create a file like what you see in this screenshot of the file in the target directory
将创建一个文件,就像您在目标目录中的文件截图中看到的一样
That will contain this output:
这将包含以下输出:
Your Name Here
Beginning Date/Time: 2016-09-16_141048.log
Your Name Here
Ending Date/Time: 2016-09-16_141048.log
Also keep in mind that this solution is locale-dependent, so be careful how/when you use it.
还请记住,此解决方案依赖于语言环境,因此请注意使用方式/时间。
回答by Magoo
echo some output >"your logfile"
or
或者
(
echo some output
echo more output
)>"Your logfile"
should fill the bill.
应该填写账单。
If you want to APPEND
the output, use >>
instead of >
. >
will start a new logfile.
如果要APPEND
输出,请使用>>
而不是>
. >
将启动一个新的日志文件。
回答by saif
@echo off
>output.txt (
echo Checking your system infor, Please wating...
systeminfo | findstr /c:"Host Name"
systeminfo | findstr /c:"Domain"
ipconfig /all | find "Physical Address"
ipconfig | find "IPv4"
ipconfig | find "Default Gateway"
)
@pause
回答by AquaAlex
There is a cool little program you can use to redirect the output to a file and the console
有一个很酷的小程序可以用来将输出重定向到文件和控制台
some_command ^| TEE.BAT [ -a ] filename
@ECHO OFF
:: Check Windows version
IF NOT "%OS%"=="Windows_NT" GOTO Syntax
:: Keep variables local
SETLOCAL
:: Check command line arguments
SET Append=0
IF /I [%1]==[-a] (
SET Append=1
SHIFT
)
IF [%1]==[] GOTO Syntax
IF NOT [%2]==[] GOTO Syntax
:: Test for invalid wildcards
SET Counter=0
FOR /F %%A IN ('DIR /A /B %1 2^>NUL') DO CALL :Count "%%~fA"
IF %Counter% GTR 1 (
SET Counter=
GOTO Syntax
)
:: A valid filename seems to have been specified
SET File=%1
:: Check if a directory with the specified name exists
DIR /AD %File% >NUL 2>NUL
IF NOT ERRORLEVEL 1 (
SET File=
GOTO Syntax
)
:: Specify /Y switch for Windows 2000 / XP COPY command
SET Y=
VER | FIND "Windows NT" > NUL
IF ERRORLEVEL 1 SET Y=/Y
:: Flush existing file or create new one if -a wasn't specified
IF %Append%==0 (COPY %Y% NUL %File% > NUL 2>&1)
:: Actual TEE
FOR /F "tokens=1* delims=]" %%A IN ('FIND /N /V ""') DO (
> CON ECHO.%%B
>> %File% ECHO.%%B
)
:: Done
ENDLOCAL
GOTO:EOF
:Count
SET /A Counter += 1
SET File=%1
GOTO:EOF
:Syntax
ECHO.
ECHO Tee.bat, Version 2.11a for Windows NT 4 / 2000 / XP
ECHO Display text on screen and redirect it to a file simultaneously
ECHO.
IF NOT "%OS%"=="Windows_NT" ECHO Usage: some_command 3 TEE.BAT [ -a ] filename
IF NOT "%OS%"=="Windows_NT" GOTO Skip
ECHO Usage: some_command ^| TEE.BAT [ -a ] filename
:Skip
ECHO.
ECHO Where: "some_command" is the command whose output should be redirected
ECHO "filename" is the file the output should be redirected to
ECHO -a appends the output of the command to the file,
ECHO rather than overwriting the file
ECHO.
ECHO Written by Rob van der Woude
ECHO http://www.robvanderwoude.com
ECHO Modified by Kees Couprie
ECHO http://kees.couprie.org
ECHO and Andrew Cameron
回答by Indra Permana
@echo OFF
[your command] >> [Your log file name].txt
I used the command above in my batch file and it works. In the log file, it shows the results of my command.
我在批处理文件中使用了上面的命令并且它有效。在日志文件中,它显示了我的命令的结果。
回答by ilgitano
Add these two lines near the top of your batch file, all stdout and stderr after will be redirected to log.txt:
在批处理文件顶部附近添加这两行,之后的所有 stdout 和 stderr 都将重定向到 log.txt:
if not "%1"=="STDOUT_TO_FILE" %0 STDOUT_TO_FILE %* >log.txt 2>&1
shift /1
回答by jan antonin
This may fail in the case of "toxic" characters in the input. Considering an input like thisIsAnIn^^^^put is a good way how to get understand what is going on. Sure there is a rule that an input string MUST be inside double quoted marks but I have a feeling that this rule is a valid rule only if the meaning of the input is a location on a NTFS partition (maybe it is a rule for URLs I am not sure). But it is not a rule for an arbitrary input string of course (it is "a good practice" but you cannot count with it).
如果输入中包含“有毒”字符,这可能会失败。考虑像 thisIsAnIn^^^^put 这样的输入是了解正在发生的事情的好方法。当然有一条规则,输入字符串必须在双引号内,但我有一种感觉,只有当输入的含义是 NTFS 分区上的位置时,这条规则才是有效的规则(也许这是我的 URL 规则)我不确定)。但这当然不是任意输入字符串的规则(这是“一个好习惯”,但你不能用它来计算)。