windows 如何将命令输出设置为批处理文件中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6359820/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:28:40  来源:igfitidea点击:

How to set commands output as a variable in a batch file

windowsbatch-file

提问by Dennis

Is it possible to set a statement's output of a batch file to a variable, for example:

是否可以将批处理文件的语句输出设置为变量,例如:

findstr testing > %VARIABLE%

echo %VARIABLE%

回答by Mechaflash

FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%

I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.

我总是使用USEBACKQ,这样如果您要插入一个字符串或一个长文件名,您就可以使用双引号而不会搞砸命令。

Now if your output will contain multiple lines, you can do this

现在,如果您的输出将包含多行,您可以这样做

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL

回答by dolphy

I found this threadon that there Interweb thing. Boils down to:

我在那个互联网上找到了这个线程。归结为:

@echo off 
setlocal enableextensions 
for /f "tokens=*" %%a in ( 
'VER' 
) do ( 
set myvar=%%a 
) 
echo/%%myvar%%=%myvar% 
pause 
endlocal 

You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.

您还可以将命令的输出重定向到一个临时文件,然后将该临时文件的内容放入您的变量中,就像这样。但是它不适用于多行输入。

cmd > tmpFile 
set /p myvar= < tmpFile 
del tmpFile 

Credit to the thread on Tom's Hardware.

归功于 Tom's Hardware 上的线程。

回答by Yuri

in a single line:

在一行中:

FOR /F "tokens=*" %g IN ('*your command*') do (SET VAR=%g)

the command output will be set in %g then in VAR.

命令输出将在 %g 中设置,然后在 VAR 中设置。

More informations: https://ss64.com/nt/for_cmd.html

更多信息:https: //ss64.com/nt/for_cmd.html

回答by Yuri

To read a file...

要读取文件...

set /P Variable=<File.txt

To Write a file

写入文件

@echo %DataToWrite%>File.txt

note; having spaces before the <> character causes a space to be added at the end of the variable, also

笔记; <> 字符前有空格会导致在变量末尾添加一个空格,也

To add to a file,like a logger program, First make a file with a single enter key in it called e.txt

要添加到文件,如记录器程序,首先创建一个名为 e.txt 的文件,其中包含一个输入键

set /P Data=<log0.log
set /P Ekey=<e.txt
@echo %Data%%Ekey%%NewData%>log0.txt

your log will look like this

你的日志看起来像这样

Entry1
Entry2 

and so on

等等

Anyways a couple useful things

无论如何,一些有用的东西

回答by Ryan Shillington

These answers were all so close to the answer that I needed. This is an attempt to expand on them.

这些答案都非常接近我需要的答案。这是对它们进行扩展的尝试。

In a Batch file

在批处理文件中

If you're running from within a .batfile and you want a single line that allows you to export a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.jsonto a variable named AWS_ACCESS_KEYthen you want this:

如果你在一个.bat文件中运行并且你想要一行允许你导出一个复杂的命令,比如jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json一个命名的变量,AWS_ACCESS_KEY那么你想要这个:

FOR /F "tokens=* USEBACKQ" %%g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%%g")

On the Command Line

在命令行上

If you're at the C:\prompt you want a single line that allows you to run a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.jsonto a variable named AWS_ACCESS_KEYthen you want this:

如果你在C:\提示符下你想要一行允许你运行一个复杂的命令,比如jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json一个名为变量的命令,AWS_ACCESS_KEY那么你想要这个:

FOR /F "tokens=* USEBACKQ" %g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%g")

Explanation

解释

The only difference between the two answers above is that on the command line, you use a single % in your variable. In a batch file, you have to double up on the percentage signs (%%).

上面两个答案之间的唯一区别是,在命令行上,您在变量中使用了一个 %。在批处理文件中,您必须将百分比符号 (%%) 加倍。

Since the command includes colons, quotes, and parentheses, you need to include the USEBACKQline in the options so that you can use backquotes to specify the command to run and then all kinds of funny characters inside of it.

由于命令包含冒号、引号和括号,因此您需要USEBACKQ在选项中包含该行,以便您可以使用反引号指定要运行的命令,然后在其中包含各种有趣的字符。

回答by Zimba

If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

如果您不想输出到临时文件然后读入变量,则此代码将命令的结果直接存储到变量中:

FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
echo %VARIABLE%

If you want to enclose search string in double quotes:

如果要将搜索字符串括在双引号中:

FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i

If you want to store this code in a batch file, add an extra % symbol:

如果要将此代码存储在批处理文件中,请添加额外的 % 符号:

FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i

A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

计算目录中文件数并存储在变量中的有用示例:(说明管道)

FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i

Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokensor usebackqin forloop.

注意使用单引号,而不是在命令括号双引号“或重音符'的,这是更清洁的替代delimstokensusebackqfor循环。

Tested on Win 10 CMD.

在 Win 10 CMD 上测试。

回答by Dado

cd %windir%\system32\inetsrv

@echo off

for /F "tokens=* USEBACKQ" %%x in (      
        `appcmd list apppool /text:name`
       ) do (
            echo|set /p=  "%%x - " /text:name & appcmd.exe list apppool "%%x" /text:processModel.identityType
       )

echo %date% & echo %time%

pause

回答by QcAlexN

I have tested it like this and it worked:

我已经像这样测试过它并且它有效:

SET /P Var= | Cmd

By piping the command into a variable, prompt will insert the result of command "Cmd" into the variable "Var".

通过管道将命令放入一个变量中,prompt 会将命令“ Cmd”的结果插入到变量“ Var”中。

Update:

更新:

It doesn't work, my bad, the script i did was this:

它不起作用,我的错,我做的脚本是这样的:

SET /P Var= | dir /b *.txt
echo %Var%

It was actually showing let's say "test.txt", but it was in fact showing the result of the "dir /b *.txt" command, not the echo %var%. I got confused since both outputs were the same.

它实际上显示了“ test.txt”,但实际上显示的是“ dir /b *.txt”命令的结果,而不是echo %var%. 我很困惑,因为两个输出是相同的。

回答by Ben2014

Hope this help

希望这有帮助

set a=%username%
echo %a%    
set a="hello"
echo %a%