Batch file: suppress command error output when used in for loop

I repeat the output of the command in a for loop. Consider the following code:

for /F "tokens=1 delims=?=" %%A in ('set __variable') do ( set %%A= )

Basically, I am trying to clear the value of each environment variable whose name begins with "__variable". However, if such a variable is not set, I get the error "Environment variable __variable not defined", which is not what I would like to display on my console. Therefore, naturally, I would modify my code as follows:

for /F "tokens=1 delims=?=" %%A in ('set __variable 2> NUL') do ( set %%A= )

But now I get a new error stating that "2> was unexpected at the moment." or something like that. Now i'm stuck; is there any way for me to complete my task without causing a standard error on the screen?

+5
source share
1 answer

For Windows NT 4 and later, you will need to remove the channel and redirection characters, which are done by prefixing them with carets ():

for /F "tokens=1 delims=?=" %A in ('set __variable 2^>NUL') do ( set %A= )
+10
source

All Articles