visionviper
visionviper

Reputation: 3

Batch file for loop appears to be running one extra time/iteration

I'm trying to put a batch file together to run a program on each logical drive on a system except for optical drives. It filters out the optical drives just fine but for some reason my echo of the built up command I am testing with runs one extra time except the variables have no values. It's like the loop is iterating an extra time on a null value. Ideas?

(The IF NOT !drive! == %safe% is just making sure I don't run the command for the drive the script lives on and "safe" is just an acronym)

for /F "usebackq skip=1 tokens=1,2" %%a IN (`wmic logicaldisk get DeviceID^,DriveType`) do (
    SET drive=%%a
    SET driveType=%%b
    IF NOT !drive! == %safe% (
        IF NOT !driveType! == 5 (
        ECHO test commands
        )
    )
)

Upvotes: 0

Views: 761

Answers (1)

Mark
Mark

Reputation: 3700

wmic puts an additional carriage return at the end of its resulting report. Try something like this:

for /f "skip=1 tokens=1,2" %%a IN ('wmic logicaldisk get DeviceID^,DriveType ^| findstr /v /r /c:"^$"') do (
    SET drive=%%a
    SET driveType=%%b
    IF NOT !drive! == %safe% (
        IF NOT !driveType! == 5 (
            ECHO test commands
        )
    )
)

Note: usebackq isn't required since your command doesn't include forward-ticks. The findstr there just searches for a blank line (that is, the regex is "beginning of line followed by end of line").

Upvotes: 1

Related Questions