Subham Tripathi
Subham Tripathi

Reputation: 2733

How to redirect error stream to variable

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"
    )

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?

Upvotes: 2

Views: 3979

Answers (2)

Darth
Darth

Reputation: 11

To get std error to a variable, I created a FOR loop that redirects both std in and err to a findstr command which then lets you capture the text you are looking for.

FOR /F "eol=; tokens=1-2 delims=" %a in ('*command* 2^>^&1^|findstr /I "*text*"') do (set x=%a)

Upvotes: 1

DavidPostill
DavidPostill

Reputation: 7921

To store the first line only:

set /p var=<temp.txt

Something like:

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

To store multiple lines:

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

Source Set - Display, set, or remove CMD environment variables

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

Set /P _MyVar=<MyFilename.txt

Upvotes: 1

Related Questions