windows 将批处理文件(.bat 文件)中的值返回到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/737098/
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
Return a value from batch files (.bat file)to a text file
提问by Maddy
I have a .bat file shown below
我有一个 .bat 文件如下所示
@echo off
for /f "delims=" %%a in ('C:\MyProj\Sources\SearchString.vbs') do (
set ScriptOut=%%a)
#echo Script Result = %ScriptOut%
echo %ScriptOut% >C:\ThreePartition\Sources\myfile.txt
I want my output variable which is ScriptOut to be stored into a text file. Can anyone suggest any method to be added to my existing batch file.
我希望将我的输出变量 ScriptOut 存储到文本文件中。任何人都可以建议将任何方法添加到我现有的批处理文件中。
Thanks Maddy
谢谢麦迪
回答by Stanislav Kniazev
Do I understand correctly that your file gets overwritten and you want it appended? If so, try this:
我是否正确理解您的文件被覆盖并希望附加它?如果是这样,试试这个:
echo %ScriptOut% >> C:\ThreePartition\Sources\myfile.txt
(note the double ">>")
(注意双“>>”)
回答by Joey
The for
loop you have there executes that script and runs for every line the script returns. Basically this means that your environment variable %ScriptOut%
contains only the lastline of the output (since it gets overwritten each time the loop processes another line). So if your script returns
for
您在那里的循环执行该脚本并为脚本返回的每一行运行。基本上这意味着您的环境变量%ScriptOut%
仅包含输出的最后一行(因为每次循环处理另一行时它都会被覆盖)。所以如果你的脚本返回
a
b
c
then %ScriptOut%
will contain only c
. If the last line is empty or contains only spaces iot will effectively delete %ScriptOut%
which is why when you do an
那么%ScriptOut%
将只包含c
. 如果最后一行为空或仅包含空格,iot 将有效删除%ScriptOut%
这就是为什么当您执行
echo %ScriptOut%
you'll only get ECHO is on.
since after variable substition all that's left there is echo
. You can use
你只会得到ECHO is on.
因为在变量替换之后剩下的所有东西echo
。您可以使用
echo.%ScriptOut%
echo.%ScriptOut%
in which case you'll be getting an empty line (which would be what %ScriptOut%
contains at that point.
在这种情况下,您将得到一个空行(这将是当时%ScriptOut%
包含的内容。
If you want to print every line the script returns to a file then you can do that much easier by simply doing a
如果您想打印脚本返回到文件的每一行,那么您可以通过简单地执行以下操作来轻松完成
cscript C:\MyProj\Sources\SearchString.vbs > C:\ThreePartition\Sources\myfile.txt
or use >>
for redirection if you want the output to be appended to the file, as Stanislav Kniazev pointed out.
或>>
用于重定向,如果您希望将输出附加到文件中,正如Stanislav Kniazev 指出的那样。
If you just want to store the last non-emptyline, then the following might work:
如果您只想存储最后一个非空行,那么以下可能有效:
for /f "delims=" %%a in ('C:\MyProj\Sources\SearchString.vbs') do (
if not "%%a"=="" set ScriptOut=%%a
)
which will only set %ScriptOut%
in case the loop variable isn't empty.
只有%ScriptOut%
在循环变量不为空的情况下才会设置。