I'm trying to do a script that will run constantly in background. Its goal is to detect USB flash drives, external hard drives, or any writable device that you'd connect to your computer. Once it detected one, it'd copy a file at the root of this device. Here's my code (the echo lines are for clearer debugging):
@echo off
:loop
for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do (
for %%c in (%%b) do (
for /F "tokens=4" %%d in ('fsutil fsinfo drivetype %%c') do (
if %%d equ amovible (
echo Found out that %%c is removable. Trying to echo the content...
dir %%c >NUL
echo Error: %errorlevel%
if %errorlevel%==0 (
echo Errorlevel is 0! Copying...
if not exist %%c\test.txt (
copy .\test.txt %%c\test.txt
echo.
)
) else (
echo Errorlevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
echo.
)
)
)
)
)
TIMEOUT 2
goto :loop
And here's the problem. The condition "if %errorlevel%==0" is supposed to check if the "dir %%c >NUL" command succeeded, so if errorlevel is 0, that means there's a filesystem on the device, and it's not like an empty card reader or an empty floppy drive. The thing is when I execute my code, errorlevel is always 0, and I can't figure out why ("echo Error: %errorlevel%" tells it). So the file test.txt does copy on my USB flash drive, so this basically work, the thing is when it comes to copy the file to my floppy drive, an error box shows up, saying that I should insert a device in the reader, that's why I want to do this errorlevel check.
So if someone has a solution, please help, I'm really stuck. Thanks in advance.
!ErrorLevel!
), because otherwise, you get theErrorLevel
present when the entire parenthesised block (loop) is parsed... – aschipflif not errorlevel 1 ...
which doesn't need delayed expansion. – user6811411for %%c in (%%b) do ( ... )
intended for? – aschipflfsutil fsinfo drives
commande lists the differents drive letters, so thefor
loop is used to check them one by one – Nim