Luis
Luis

Reputation: 13

Setting a variable from a text file

I have the following:

FOR /f "tokens=*" %%a IN (%input%) do (
dsquery * forestroot -filter "(&(mail=%%a))" | dsget user -UPN >> p.txt 2> tmp.txt
set /p Error=<tmp.txt
echo %%a %Error% >> log.txt
)

The point is to create a list of usernames from a list of emails by querying an AD, which is not a problem. But I also want to send the errors to a log file, and something doesn't seem to be working when I send the temp.txt into the variable (I tried to add "echo %Error%" and all it says is "Echo is off"

Upvotes: 1

Views: 60

Answers (1)

Stephan
Stephan

Reputation: 56155

You are using %error% in a block statement for ... in (...) do (this is a block)

A block is evaluated in one go, but you are changing the variable inside the block. To get the changed variable, use delayed expansion: At the start of your script write

setlocal enabledelayedexpansion

and inside the block use the (changed) value with !error! instead of %error%

Changing

echo %%a %Error% >> log.txt

to

echo %%a !Error! >> log.txt

should solve your problem (together with the setlocal enabledelayedexpansion).

Upvotes: 2

Related Questions