开发者

Batch script variable not working right

Well... I try to dabble in batch as little as possible, and I'm mainly a C/C#/C++ man. My problem is that my scr开发者_StackOverflow社区ipt does two nested FOR loops where I run through the 'Users' folder first and snag the user names and then through other folders:

 set BaseDir=%CD%
 cd C:\Users
 for /F %%I in ('DIR *.* /B /O:-D') do (
     set UserName=%%I
     echo %UserName%
 )
 cd %BaseDir%

This roughly demonstrates the problem. Maybe it's my C++ style formatting? Maybe I'm dumb when it comes to batch? Assuming I have 3 users on my system (Admin, User1, User2; in that order) this will print:

 Admin
 Admin
 Admin

Totes wrong. If one were to call echo on %%I everything would go according to plan:

 Admin
 User1
 User2

Am I missing something here as far as variables go, or what's the deal? DOS doesn't like variable re-assignment? Thnx in advance. (specs: Windows 7, notepad, cmd as admin)


Since you are changing a variable within the FOR loop, you need to enable delayed expansions:

SETLOCAL ENABLEDELAYEDEXPANSION
cd C:\Users
for /F %%I in ('DIR *.* /B /O:-D') do (
 set UserName=%%I
 echo %UserName%
)

EDIT A neat way to assign the variables separately to access each instance outside of the loop

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
    cd C:\Users
    for /F %%I in ('DIR *.* /B /O:-D') do (
     set UserName!count!=%%I
     echo %UserName!count!%
     set count=!count!+1
    )


Another option is to use a subroutine:

 pushd C:\Users
 for /F %%I in ('DIR *.* /B /O:-D') do call :perfile %%I
 popd
 goto :eof

 :perfile
 set UserName=%*
 echo %UserName%
 goto :eof

Also note the use of pushd and popd to avoid needing to store the original directory in an environment variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜