I'm trying to write a script, which will detect the letter of my USB Removable Drive called "UUI" and then create folder on it. I've written few commands for CMD which, when run separately, work. However when I put them into a bat file, I always get some errors. Here are the commands in a bat file:
for /F "tokens=1 delims= " %i in ('WMIC logicaldisk where "DriveType=2" list brief ^| c:\windows\system32\find.exe "UUI"') do (echo %i > drive.txt)
set /p RemovableDriveLetter2= < drive.txt
del /F /Q drive.txt
set RemovableDriveLetter=%RemovableDriveLetter2:~0,1%
%RemovableDriveLetter%:
md MyNewFolder
cd MyNewFolder
When I go to cmd.exe and run the file by calling "myScript.bat" or "call myScript.bat", I get an error:
C:\Users\UUI\Desktop>myScript.bat
\windows\system32\find.exe was unexpected at this time.
C:\Users\UUI\Desktop>for /F "tokens=1 delims= " \windows\system32\find.exe "UUI"') do (echo i > drive.txt)
C:\Users\UUI\Desktop>
I can see that MyNewFolder was not created. However, when I copy all lines and run them in CMD as such (e.g. not in the .bat file) and run them one by one, it is fully functional within the cmd.exe instance.
How can I create bat a file, which will successfully run and detects the drive letter of my removable drive without issues? Or how can I solve the error "\windows\system32\find.exe was unexpected at this time."?
You need to double the
%
sign used to mark aFOR
loop control variable in a batch script (.bat
or.cmd
), i.e. use%%i
instead of%i
used in pure CLI.However, there is another possible approach how-to parse
wmic
output. See also Dave Benham'sWMIC
andFOR /F
: A fix for the trailing<CR>
problemHere the
for
loops are%%G
to retrieve theDeviceID
value;%%i
to remove the ending carriage return in the value returned:wmic
behaviour: each output line ends with0x0D0D0A
(CR+CR+LF
) instead of common0x0D0A
(CR+LF
).One could use
Caption
orName
instead ofDeviceID
:Note there could be no or more disks present having
DriveType=2
:Script output for no, then one and then two USB drive(s), respectively: