如何将错误流重定向到变量 [英] How to redirect error stream to variable

查看:129
本文介绍了如何将错误流重定向到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.我想获取错误流,在for循环中执行命令后将其放入变量中,与此同时,我将其发送到NUL来丢弃stdout.

I have the following piece of code. I want to take the error stream, put it in variable after executing the command in the for loop, and in the meantime I discard the stdout by sending it to NUL.

 for /f "delims=" %%a IN ('%test_command% 2^>^&1 1^>NUL') do (
           set err_msg="%%~a"
    )

我希望为其添加一项功能.除了将stdout发送到NUL之外,我还希望将其存储在文件中,该如何添加该功能?

I wish to add one feature to it. In addition to sending stdout to NUL I want to store it in a file, how do I to add that functionality ?

使用以下代码,我可以将输出存储到文件中:

Using the below code I can store the output to a file:

for /f "delims=" %%a IN ('%test_command% 2^>^&1 1^>temp.txt') do (
           set err_msg="%%~a"    
)

但是我想将输出存储到变量中,我该怎么做?

But I want to store the output to a variable, how can I do that?

推荐答案

仅存储第一行:

set /p var=<temp.txt

类似的东西:

do (
    set err_msg="%%~a" && set /p var=<temp.txt
)

要存储多行:

要从temp.txt中获取多行到一个变量中,请使用DelayedExpansion和第二个for循环:

To get multiple lines from temp.txt into a variable use DelayedExpansion and a second for loop:

setlocal EnableDelayedExpansion
...
for /f "Tokens=* Delims=" %%x in (temp.txt) do set var=!var!%%x


来源设置-显示,设置或删除CMD环境变量

要将文件的第一行放入变量中:

To place the first line of a file into a variable:

Set /P _MyVar=<MyFilename.txt

这篇关于如何将错误流重定向到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆