keNscale
keNscale

Reputation: 13

Windows FOR command not expanding system environment variables

I have been using this site for sometime and have found it quite valuable in finding solutions to scripting issues. Today I resolve to ask a question as I have not found my solution after exhausting 3 days here, on Superuser, and Googling. So much for all about me, now my point...

I have several installs of a program, each slightly different version or flavor. Each install has a text file defining variables for its use. One of these variables defines a folder for user specific settings, USERSET=%APPDATA%\foo1\foo2. Overtime these user settings can become corrupt. I want to be able to delete these folders with a batch file or script. In short, I want to search a directory for text files that contain a specific string which sets a variable that points to a folder, get the value of that variable and use it to remove a directory.

This is what I have so far:

for /f "tokens=2 delims==" %%G in ('dir /b /s c:\foo\*.txt ^| findstr /i /f:/ userset') do rd /s /q %%G

The output looks like this:

H:\>rd /s /q %appdata%\foo1\foo2\USERSET   
The system cannot find the file specified.

Apparently %appdata% does not expand?

Of course if I just type rd /s /q %appdata%\foo1\foo2\USERSET at the command prompt, it works.

I'm open to other languages, I am mostly familiar with Windows command line.

Upvotes: 1

Views: 98

Answers (2)

Magoo
Magoo

Reputation: 79982

I'd simply insert a CALL before the RD

....CALL RD ...

although I'd also try

....CALL ECHO(RD ...

first to verify - just for safety's sake.

Upvotes: 0

Joey
Joey

Reputation: 354406

This is because environment variable expansion is done at parse time of a statement. While your for loop is running and %%G actually gets a value it's too late; variables have already been expanded.

You can work around this with a subroutine, I guess:

pushd C:\foo
for /f ...  %%G in (...) do call :process "%%G"
popd
goto :eof

:process
  call set "X=%~1"
  rd /s /q "%X%"
  goto :eof

Upvotes: 1

Related Questions