user2859538
user2859538

Reputation: 25

Output forfiles error to a variable

I am trying to save the output of forfiles to a variable in batch.

I've tried a few things to set a var to the output directly as well as saving to a file

Long story short, I am comparing the output text to another string variable, if it matches an event log is created and I get an alert.

Everything in my script works as intended other than saving the forfile output to the variable so I can compare it to my default text variable

forfiles /P %filename% /D -1 > variable set TEST=

the variable just stays completely blank.

If I run the command just in command prompt it outputs like this

forfiles /P C:\users\justin.pcs\desktop\test\ /D -1 > variable ERROR: No files found with the specified search criteria.

So I am getting the error I am watching for, but the variable stays blank. I'm assuming I am missing some sort of switch that is necessary for this.

Upvotes: 0

Views: 842

Answers (1)

Stephan
Stephan

Reputation: 56180

to get the output of a command, either redirect STDERR to a file and read it back:

forfiles /P C:\users\justin.pcs\desktop\test\ /D -1  2>temp
<temp set /p variable=
echo %variable"%

or use a for construct (no temporary file needed):

for /f "delims=" %%a in ('forfiles /P C:\users\justin.pcs\desktop\test\ /D -1  2^>^&1 1^>nul') do set variable=%%a
echo %variable%

The redirections (2^>^&1 1^>nul)are needed, because STDOUT is parsed, but you need STDERR.

Upvotes: 0

Related Questions