Batch conditional FOR loop nested IF - batch-file

I'm trying to write a script that parses a text file to identify removable drives by Label. The goal is to create a copy script based on the found drives.
I'm able to parse the file but I can't seem to get the second pair of IF conditions to be true.
I may be misunderstanding how variables are evaluated in each loop of the FOR.
Thoughts appreciated.
EDIT: Expanding on the original request for clarity(it was late when I asked) The expanded goal is to identify one or many target drives to copy data from an SD card. Since the drives letter allocations vary from PC to PC and depend on which is plugged in first my idea was to use the labels as somewhat identifiable values and create a simple copy string along the lines of
XCOPY SourceDrive\*.jpg DestinationDrive1\<GetDate>\
XCOPY SourceDrive\*.jpg DestinationDrive2\<GetDate>\
End Edit
#echo off
cls
title "Detecting device drive letters..."
setlocal enabledelayedexpansion
set DestinationDrive1Found=
set DestinationDrive2Found=
set SourceDriveFound=
set SourceDrive=
set DestinationDrive1=
set DestinationDrive2=
echo Detecting device drive letters...
echo list volume > %systemdrive%\ListDrives.tmp
diskpart /s %systemdrive%\ListDrives.tmp > %systemdrive%\CurrentDrives.tmp
echo Checking drive IDs
FOR /F "skip=7 tokens=2-4" %%a IN (%systemdrive%\CurrentDrives.tmp) DO (
set "matchvar=%%c"
set "comparevar=!matchvar:DRIVE=!"
IF /I NOT "!comparevar!" == "%%c" IF "!DestinationDrive1Found!" NEQ 1 (
echo Drive %%b was found to be %%c and will be DESTINATION1
set DestinationDrive1Found=1
set DestinationDrive1=%%b )
IF /I NOT "!comparevar!" == "%%c" IF "!DestinationDrive1Found!" EQU 1 ( echo Drive %%b was found to be %%c and will be DESTINATION2
set DestinationDrive2Found=1
set DestinationDrive2=%%b )
)
File I'm parsing
Microsoft DiskPart version 10.0.10586
Copyright (C) 1999-2013 Microsoft Corporation.
On computer: NEWGLOOMWIN10
Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 D DVD-ROM 0 B No Media
Volume 1 E Macintosh H HFS Partition 231 GB Healthy
Volume 2 C BOOTCAMP NTFS Partition 721 GB Healthy System
Volume 3 F TEAMXCAMRAX FAT Removable 1937 MB Healthy
Volume 4 G TEAMXDRIVEX NTFS Partition 465 GB Healthy
Volume 5 H TEAMYDRIVEY NTFS Partition 931 GB Healthy

Thanks to all who responded. Had #Mofi provided an answer I would have marked that response as the answer. In the end the removal of a four quote marks and the addition of an ELSE got me the answer I was looking for.
The script below gives me exactly what I'm after.
#echo off
cls
title "Detecting device drive letters..."
setlocal enabledelayedexpansion
set DestinationDrive1Found=
set DestinationDrive2Found=
set SourceDriveFound=
set SourceDrive=
set DestinationDrive1=
set DestinationDrive2=
echo Detecting device drive letters...
echo list volume > %systemdrive%\ListDrives.tmp
diskpart /s %systemdrive%\ListDrives.tmp > %systemdrive%\CurrentDrives.tmp
echo Checking drive IDs
FOR /F "skip=7 tokens=2-4" %%a IN (%systemdrive%\CurrentDrives.tmp) DO (
set "matchvar=%%c"
set "comparevar=!matchvar:CAMRA=!"
IF /I NOT "!comparevar!" == "%%c" (#echo Drive %%b was found to be %%c and will be SOURCE
set SourceDriveFound=1
set SourceDrive=%%b)
)
echo Checking drive IDs
FOR /F "skip=7 tokens=2-4" %%a IN (%systemdrive%\CurrentDrives.tmp) DO (
set "matchvar=%%c"
set "comparevar=!matchvar:DRIVE=!"
IF /I NOT "!comparevar!" == "%%c" IF !DestinationDrive1Found! NEQ 1 (
echo Drive %%b was found to be %%c and will be DESTINATION1
set DestinationDrive1Found=1
set DestinationDrive1=%%b
) ELSE (
IF /I NOT "!comparevar!" == "%%c" IF !DestinationDrive1Found! EQU 1 ( echo Drive %%b was found to be %%c and will be DESTINATION2
set DestinationDrive2Found=1
set DestinationDrive2=%%b ))
)

If you just want to set some variables to the drives allocated to any removable drive with the string DRIVE in it's 'label' then the following may provide you with an alternative not requiring elevation.
#Echo Off
For /F "UseBackQ Skip=1 Delims=" %%A In (`WMIC LogicalDisk Where^
"DriveType='2' And VolumeName Like '%%DRIVE%%'" Get Name`
) Do For /F %%B In ("%%A") Do Set/A "i+=1"&Call Set "_drv%%i%%=%%B"
Set _drv
Timeout -1
[Edits] - an example correctly stipulating a fixed drive
#Echo Off
For /F "UseBackQ Skip=1 Delims=" %%A In (`WMIC LogicalDisk Where^
"DriveType='3' And VolumeName Like '%%DRIVE%%'" Get Name`
) Do For /F %%B In ("%%A") Do Set/A "i+=1"&Call Set "_drv%%i%%=%%B"
Set _drv
Timeout -1
An example without stipulating the type of drive, (recommended based on comments).
#Echo Off
For /F "UseBackQ Skip=1 Delims=" %%A In (
`WMIC LogicalDisk Where "VolumeName Like '%%DRIVE%%'" Get Name`
) Do For /F %%B In ("%%A") Do Set/A "i+=1"&Call Set "_drv%%i%%=%%B"
Set _drv
Timeout -1

Related

sorter using scored keywords is acting up, and cannot echo without failing

this script sorts files into known subdirectories fast, by using database files filled with scored keywords. it works for the most part but sometimes it gives me errors that I can't figure out because it acts differently when the echo is turned on, and fails. this code is very important to me so this is a huge problem for me. the echo issue has to be fixed or it's unmanageable, no other possible problems need be addressed in this question! please help, it's largely beyond my understanding.
:: sorts files from %cd% into known subdirs according to database of scored keywords. minimum score is 2.0
rem todo if echo is on it fails with certain keywords like a simple *1x0* which is super weird
rem sometimes outputs unlocated error missing operator while still doing its job correctly
rem sometimes outputs unlocated error the system cannot fing the path specified
rem keywords or subdir names cannot contain spaces
rem fails with filenames with irregular dash characters
rem Adds * to start and end of keyword. start/end wildcards should be used surgically in the keywords file instead
dir *.* /a-d >nul 2>nul || exit /b
set "tempfile=%temp%\sortables"
set "sourcedir=%~1"
setlocal enabledelayedexpansion
rem set datafile, categories according to current location
set "categories="
if /i "%cd%"=="d:\videos" (
set "datafile=videos"
set "categories=series porno"
)
if /i "%cd%"=="d:\videos\movies" (
set "datafile=movies"
set "categories=features psychedelic pornography concerts standup featurettes documentaries"
)
if /i "%cd%"=="d:\videos\movies\documentaries" (
set "datafile=docu"
set "categories=1-scarcity 2-globalists 3-disinformation 4-agendas 5-abundance"
)
if /i "%cd%"=="d:\videos\movies\features" (
set "datafile=films"
set "categories=comedy drama action thriller venture crime horror mystery fantasy science western warfare"
)
if /i "%cd%"=="d:\videos\series" (
set "datafile=series"
set "categories=comedy stories reality trippy"
)
if /i "%cd%"=="d:\videos\series\comedy" (
set "datafile=comedy"
set "categories=cartoon classic modern reality sketch standup"
)
if /i "%cd%"=="d:\videos\series\pilots" (
set "datafile=pilots"
set "categories=reality drama comedy scifi fantasy crime mystery action thriller"
)
if /i "%cd%"=="d:\videos\shorts" (
set "datafile=shorts"
set "categories=psychedelic entertaining music media useful conspiracies"
)
if /i "%cd%"=="d:\videos\shorts\media" (
set "datafile=media"
set "categories=trailers games fandom extras facts analysis features"
)
if /i "%cd%"=="d:\videos\shorts\music" (
set "datafile=music"
set "categories=bigbeat classical clubbing country electro swing reggae dub experimental geeky metal rap rock synthwave triphop xxx"
)
if not defined categories exit /b
set database=d:\system\scripts\%datafile%.txt
if not exist "%database%" echo critical error: database %datafile%.txt doesn't exist && exit /b
if defined verbal echo sorting "%cd%"
rem =============================================================================================================================
rem setup sorting categories (do not change anything lightly or without backup after this point)
rem =============================================================================================================================
set "sortingcategories="
for %%a in (%categories%) do set "sortingcategories=!sortingcategories!,%%~a"
set "sortingcategories=%sortingcategories: =_%"
rem =============================================================================================================================
rem create tempfile containing lines of: name|sortingcategory|weight
rem =============================================================================================================================
(
for /f "tokens=1,2,*delims=," %%s in (%database%) do (
set "sortingcategory=%%s"
set "sortingcategory=!sortingcategory: =_!"
for /f "delims=" %%a in (
'dir /b /a-d "%sourcedir%\*%%u*" 2^>nul'
) do (
echo %%a^|!sortingcategory!^|%%t^|%%s^|%%u
)
)
)>"%tempfile%"
type "%tempfile%" >>d:\system\scripts\sorter.log
rem =============================================================================================================================
rem reset and call processing for each file in tempfile + dummy (helps counting the last score?)
rem =============================================================================================================================
set "lastname="
echo off
for /f "tokens=1,2,3,*delims=|" %%a in ('sort "%tempfile%"') do call :resolve %%b %%c "%%a"
call :resolve dummy 0
rem declare failures
if defined verbal if not "%datafile%"=="videos" if not "%datafile%"=="music" if not "%datafile%"=="media" (
dir "%~1\*" /a-d >nul 2>nul && for /f "delims=" %%q in ('dir %1 /b /a-d') do echo unsortable in %datafile% "%%q"
)
exit /b
:resolve
IF "%~3" equ "%lastname%" GOTO accum
rem report and reset accumulators
IF NOT DEFINED lastname GOTO RESET
SET "winner=none"
SET /a maxfound=1
FOR %%v IN (%sortingcategories%) DO (
FOR /f "tokens=1,2delims=$=" %%w IN ('set $%%v') DO IF %%x gtr !maxfound! (SET "winner=%%v"&SET /a maxfound=%%x)
)
if "%winner%"=="none" goto reset
SET "winner=%winner:_= %"
SET "lastname=%lastname:&=and%"
rem this has a problem with different type of dash -
rem this once overwrote a same-name, much smaller file, wtf?
if "%winner%"=="porno" move "%sourcedir%\%lastname%" "d:\nvidia\" >nul && echo "d:\nvidia\%lastname%"
if not "%winner%"=="porno" move "%sourcedir%\%lastname%" "%sourcedir%\%winner%\" >nul && echo "%sourcedir%\%winner%\%lastname%"
if "%winner%"=="features" if exist "%sourcedir%\%lastname%" move "%sourcedir%\%lastname%" "%sourcedir%\%winner%\" >nul && echo "%sourcedir%\%winner%\%lastname%"
rem before or after successful filing we could do a surgical dupe check for only that file, rendering the old style obsolete
:RESET
FOR %%v IN (%sortingcategories%) DO SET /a $%%v=0
SET "lastname=%~3"
:accum
SET /a $%1+=%2
with echo turned on the error looks like this (note that this works fine when echo is off)
d:\VIDEOS>for /F "tokens=1,2,3,*delims=|" %a in ('sort "E:\TEMP\sortables"') do call :resolve %b %c "%a"
d:\VIDEOS>call :resolve !sortingcategory! 2 " for /F "delims=" %a in ('dir /b /a-d "\*1x0*" 2>nul') do (echo %a"
The syntax of the command is incorrect.
d:\VIDEOS>IF " for /F "delims" equ "" GOTO accum
d:\VIDEOS>
and this is the database file used (sorry for the lingo)
series,2,1x0
series,2,1x1
series,2,2x0
series,1,s0
series,1,s1
series,1,s2
series,1,s3
series,1,s4
series,1,s5
series,1,s6
series,1,s7
series,1,s8
series,1,s9
series,-1,s00
series,-1,e00
series,1,e0
series,1,e1
series,1,e2
series,1,e3
series,1,e4
series,1,e5
series,1,e6
series,1,e7
series,1,e8
series,1,e9
series,-1,extras
series,1,judge?judy?s
series,1,pilot
porno,1,amateur
porno,1,wet
porno,1,wmv
porno,1,xxx
missing,0,not appearing in this directory
it takes files from d:\videos and sorts them into d:\videos\series or d:\nvidia (hidden alternative to the other subdir d:\videos\porno)
rem =============================================================================================================================
rem create tempfile containing lines of: name|sortingcategory|weight
rem =============================================================================================================================
(
for /f "tokens=1,2,*delims=," %%s in (%database%) do (
set "sortingcategory=%%s"
set "sortingcategory=!sortingcategory: =_!"
for /f "delims=" %%a in (
'dir /b /a-d "%sourcedir%\*%%u*" 2^>nul'
) do (
echo %%a^|!sortingcategory!^|%%t^|%%s^|%%u
)
)
)>"%tempfile%"
change to
rem =============================================================================================================================
rem create tempfile containing lines of: name|sortingcategory|weight
rem =============================================================================================================================
(
for /f "usebackq tokens=1,2,* delims=," %%s in ("%database%") do (
set "sortingcategory=%%s"
set "sortingcategory=!sortingcategory: =_!"
for /f "delims=" %%a in (
'dir /b /a-d "%sourcedir%\*%%u*" 2^>nul'
) do (
>&3 echo %%a^|!sortingcategory!^|%%t^|%%s^|%%u
)
)
) 3>"%tempfile%"
Prior, echo off setting allows the echoed text
to be redirected to file from stream 1.
When you set echo on, stream 1 includes the commands
being echoed as well as the echoed text.
To avoid this merged output of commands and text,
use an auxiliary stream. CMD supports auxiliary
streams 3 through to 9.
The changed code sets the echoed text to redirect
to the handle of stream 3 (>&3).
The redirection to the file uses stream 3 (3>).
The errors posted is a delayed effect caused by
echoed commands and text written to %tempfile%
when using echo on with your posted code.
Added for loop option usebackq so the %database%
path can be double quoted.

Batch file - Switch USB from read/write to read-only and vice versa

I was wondering if you can write a Batch file to make a USB from read/write to read-only and visa versa?
What the program should do is, if you double click on the batch file it searches for the USB drive, check if it is read/write or just read-only then swaps it to the other setting.
EDIT
I know the name of the USB and also the drive letter.
EDIT
I need this for work where we use USB drives to install programs on peoples laptops, we used CD's before, but they get lost inside.
Code would be appreciated, but directions to sites will help as well.
Tested and works flawlessly with the 4 drives I have tested.
I have the below for you if you would like. It requires 3 files though. The batch then 1 text file per each Read only or Read Write command. Simple setup but requires you to have an input, it will overwrite what ever it currently is to what ever you select.
Thanks JBin for advising that it needs to be run as Administrator, I forgot that was a thing.
cls
#Echo OFF
#Echo Toggle between read only and Read write
:choice
set /P c=Change to [R]ead Only or Read/[W]rite?
if /I "%c%" EQU "R" goto :read
if /I "%c%" EQU "W" goto :write
:read
DISKPART /s Readonly.txt
cls
#Echo -----------------------
#Echo ^| Disk is now READ ONLY ^|
#Echo -----------------------
#Echo.
goto :choice
:write
DISKPART /s Readwrite.txt
cls
#Echo ------------------------
#Echo ^| Disk is now READ WRITE ^|
#Echo ------------------------
#Echo.
goto :choice
Make two text files with the below in them. Name them what ever you like but dont forget to change the *.txt in the batch. This is also assuming you only have 1 usb device plugged into the computer
Readonly.txt file:
Sel disk 1
att dis set readonly
exit
Readwrite.txt file:
sel disk 1
att dis clear readonly
exit
It is possible to do this is Batch (via Diskpart command), but it will be VERY convoluted.
Anyways, this code detects removable drives (so floppies, I think, are included), creates a menu, then swaps the setting (read-only/read-write). It makes flash drives "write-protected", but I tested my code...
#echo off
setlocal enabledelayedexpansion
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Detect removable drives using DiskPart...
set "diskcnt=0"
for /f "tokens=1-2 delims= " %%A in (
'^(echo list disk^)^|diskpart^|findstr /ic:"Online"'
) do (
for /f "tokens=1-3 delims= " %%X in (
'^(echo select disk %%B^&echo detail disk^)^|diskpart^|findstr /ic:"Removable"'
) do (
set /a diskcnt+=1
set "vol!diskcnt!=%%B_%%Z:"
)
)
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::After detecting drives, print a menu...
echo.The script detected %diskcnt% removable drive/s:
echo.
if %diskcnt% equ 0 echo No drives found.
for /l %%X in (1,1,%diskcnt%) do (
echo. %%X. Drive !vol%%X:~2,2!
)
echo.
:choice_loop
set /p "choice=Choose a Number: "
if !choice! geq 1 if !choice! leq %diskcnt% goto :doIt
goto choice_loop
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Get and set the setting...
:doIt
echo.
set "disknum=!vol%choice%:~0,1!"
for /f "tokens=1-2 delims=:" %%F in (
'^(echo select disk %disknum%^&echo attribute disk^)^|diskpart^|findstr /bic:"Read-Only"'
) do (
set "ro_state=%%G"&set "ro_state=!ro_state: =!"
)
if /i "%ro_state%" equ "No" (
(echo select disk %disknum%&echo attribute disk set readonly)|diskpart >nul
echo Drive !vol%choice%:~2,2! is now read-only from being read/write.
) else (
(echo select disk %disknum%&echo attribute disk clear readonly)|diskpart >nul
echo Drive !vol%choice%:~2,2! is now read/write from being read-only.
)
endlocal
pause
EDIT: My only concern here is that this is language dependent, so this will not work if the language is not English.
EDIT #2: Forgive me from misunderstanding the problem. If you already have a USB name to be modified, then try this: (Make sure there are no 2 flash drives with the same name that are plugged in at the same time.)
#echo off
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Put the name of flash drive here... (Case-sensitive)
set "name=[PUT NAME HERE]"
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Detect that removable drive using DiskPart...
set "disk_num="
for /f "tokens=1-2 delims= " %%A in (
'^(echo list disk^)^|diskpart^|findstr /ic:"Online"'
) do (
for /f "tokens=1-4 delims= " %%W in (
'^(echo select disk %%B^&echo detail disk^)^|diskpart^|findstr /ic:"Removable"'
) do (
if "%%Z"=="%name%" set "disk_num=%%B"
)
)
if not defined disk_num (
echo Flash drive '%name%' not found.
goto end_this
)
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Get and set the setting...
for /f "tokens=1-2 delims=: " %%F in (
'^(echo select disk %disk_num%^&echo attribute disk^)^|diskpart^|findstr /bic:"Read-Only"'
) do (
set "ro_state=%%G"
)
if /i "%ro_state%" equ "No" (
(echo select disk %disk_num%&echo attribute disk set readonly)|diskpart >nul
echo Flash drive '%name%' is now read-only from being read/write.
) else (
(echo select disk %disk_num%&echo attribute disk clear readonly)|diskpart >nul
echo Flash drive '%name%' is now read/write from being read-only.
)
:end_this
pause
exit /b
EDIT #3: For Windows 8 and up, Run the Batch Files as Administrator for this to work.

diskpart select by disk label

I need to select a disk in WinPE using DISKPART by label. I found this but I think it's outdated:
#Echo %dbg%Off
::
:: Find External drive and set it active
:: Lists Disk Information using Diskpart
::
SetLocal EnableDelayedExpansion
:: Type the frst 11 characters of the label of the drive here.
Set _FindLabel=Recovery
Call :_InitVars "%_FindLabel%"
"%SystemRoot%\system32\FSUTIL.exe">Nul 2>&1||Goto _NotAdmin
Echo.
Echo.Please wait, gathering info on the installed drives
Echo.
>"%_Dscr1%" Echo.List disk
For /F "Tokens=2" %%I In ('Diskpart /S "%_Dscr1%"^|Findstr /I /R /C:"Disk [0-9]"') Do (
(Echo.Select Disk %%I
Echo.Detail Disk)>>"%_OFile1%"
)
For /F "Tokens=1,2,3*" %%I In ('Diskpart /S "%_OFile1%"^|Findstr /I /R /C:"Disk [0-9]" /C:"Volume [0-9]"') Do (
If /I %%I==Disk (
Set _Tmp=%%J:
) Else (
Set _Label=%%L
Set _Label=!_Label:~,11!
>>"%_OFile2%" Echo.!_Tmp!%%J:!_Label!
))
If Exist "%_OFile1%" Del "%_OFile1%"
For /F "Usebackq Tokens=1-3 Delims=:" %%I In ("%_OFile2%") Do (
Set _Label=%%K
Set _Label=!_Label:~,11!
If "!_Label!"=="%_FindLabel%" (Set _Disk=%%I) & (Set _Label=%%K) & Goto _FDisk
>>"%_OFile1%" Echo.Volume %%J on Disk %%I has the Label %%K
)
Echo.
Echo.There is no drive connected that has the label of "%_FindLabel%"
Echo.These are the currently connected volumes:
Type "%_OFile1%"
:_Exit
Echo.
Pause
Goto _Cleanup
:_FDisk
(Echo.Select disk %_Disk%
Echo.Select Partition 1
Echo.Active)>"%_Dscr1%"
Diskpart /S "%_Dscr1%"
:_Cleanup
For %%I In ("%_Dscr1%" "%_OFile1%" "%_OFile2%") Do Del %%I>Nul 2>&1
Goto :EOF
::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Subroutines
::::::::::::::::::::::::::::::::::::::::::::::::::::::
:_NotAdmin
Ver|Findstr /I /C:"Version 5">Nul
If %Errorlevel%==0 (Set _Tmp1=5) & (Set _Tmp=a Computer Administrator account)
Ver|Findstr /I /C:"Version 6">Nul
If %Errorlevel%==0 (Set _Tmp1=6) & (Set _Tmp=an Elevated Command Prompt)
Echo.
Echo.This program must be run from %_Tmp%.
If %_Tmp1%==6 Echo.Please Right click the file, then click Run as Administrator
Echo.Exiting program
Goto _Exit
:_InitVars
For /F "Tokens=1 Delims==" %%I In ('Set _ 2^>Nul') Do Set %%I=
Set _Dscr1=%temp%\dpscr1.txt
Set _OFile1=%temp%\_OFile1.txt
Set _OFile2=%temp%\_OFile2.txt
Set _FindLabel=%~1
Set _FindLabel=%_FindLabel:~,20%
Call :_Cleanup
When I run it, it returns:
Please wait, gathering info on the installed drives
There is no drive connected that has the label of "Recovery"
These are the currently connected volumes:
Volume 1 on Disk 0 has the Label NTFS Part
Volume 2 on Disk 0 has the Label NTFS Part
Volume 3 on Disk 1 has the Label WINPE
It's showing the Fs (filesystem), not the label.
Diskpart output (list volume)
Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 D USBBOOT UDF DVD-ROM 329 MB Healthy
Volume 1 Windows NTFS Partition 40 GB Healthy
Volume 2 Recovery NTFS Partition 19 GB Healthy
Volume 3 Z WINPE FAT32 Removable 7632 MB Healthy
Not sure how to modify this to get it to select the Label column.
As there is missing valid drive letter in some lines of the Diskpart output (list volume, column ltr), then tokens in line #19
For /F "Tokens=1,2,3*" %%I In ('Diskpart /S "%_OFile1%"^|Findstr /I /R /C:"Disk [0-9]" /C:"Volume [0-9]"') Do (
display as follows (and we have our culprit now):
%%I %%J %%K %%L
Volume 0 D USBBOOT UDF DVD-ROM 329 MB ...
Volume 1 Windows NTFS Partition 40 GB Healthy
Volume 2 Recovery NTFS Partition 19 GB Healthy
Volume 3 Z WINPE FAT32 Removable 7632 MB ...
Therefore you could use next snippet code (instead of lines 19..26) in your script:
For /F "Tokens=1*" %%I In ('Diskpart /S "%_OFile1%"^|Findstr /I /R /C:"Disk [0-9]" /C:"Volume [0-9]"') Do (
If /I %%I==Disk (
Set _Tmp=%%J:
) Else (
Set _Label=%%J
Set _Label=!_Label:~10,11!
>>"%_OFile2%" Echo.!_Tmp!%%J:!_Label!
))
Care this change interferes _Tmp variable!

Finding which drives are connected to computer

I have a small side project I've been working on and i want to add an option to scan the computer and find which drives are connected and what they are(USB, Hard drive, Disc drive, SSD, etc.)
this is what i have so far.
echo off
:start
color 0a
cls
title Search
echo To search enter the drive and term you wish to search below.
echo ---------------------------------------------------------------------------
set inputdrive=
set /p inputdrive=Drive:
set input=
set /p input=Search:
dir %inputdrive%:\%input% /s /b
pause
echo search again?
set inputsearch=
set /p inputsearch=(Y/N)
if %inputsearch%==Y goto start
if %inputsearch%==N exit
I plan on adding an option to scan for connected drives at the beginning of the script.
You can use WMIC to get the info without the need for administrator rights.
Here is code that gives a nice listing of all available drives, including removable media drives that do not have any media installed:
#echo off
setlocal
set ^"driveTypes=^
0Unknown :^
1No Root Directory:^
2Removable Media :^
3Local Disk :^
4Network Drive :^
5CD/DVD :^
6RAM Disk :^"
echo Available Drives:
echo(
echo ID Drive Type Volume Name
echo -- ----------------- -----------
for /f "skip=1 tokens=1-3" %%A in (
'"wmic logicalDisk get DeviceID, DriveType, VolumeName"'
) do if "%%B" neq "" (
setlocal enableDelayedExpansion
for /f "delims=:" %%D in ("!driveTypes:*%%B=!") do (
endlocal
echo %%A %%D %%C
)
)
Just a bit more code will restrict the list to only drives that are available with media:
#echo off
setlocal
set ^"driveTypes=^
0Unknown :^
1No Root Directory:^
2Removable Media :^
3Local Disk :^
4Network Drive :^
5CD/DVD :^
6RAM Disk :^"
echo Available Drives:
echo(
echo ID Drive Type Volume Name
echo -- ----------------- -----------
for /f "skip=1 tokens=1-3" %%A in (
'"wmic logicalDisk get DeviceID, DriveType, VolumeName"'
) do if "%%B" neq "" dir %%A >nul 2>nul && (
setlocal enableDelayedExpansion
for /f "delims=:" %%D in ("!driveTypes:*%%B=!") do (
endlocal
echo %%A %%D %%C
)
)
fsutil fsinfo drives
fsutil fsinfo drivetype c:
But you need to have administrator rights to use it

Detect USB and copy *.* to USB drive using batch script

I am trying to write a batch script to detect a USB drive and, if it is plugged in,
for example copy c:\test\big.txt to the USB drive, and looping to detect another flash drive.
#echo off
for %%d in (D: E: F: G: H: I: etc...) do (
if exist %%d\nul (
echo USB at drive %%d connected
)
)
EDIT: Below is the right way to do that:
#echo off
for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do (
for %%c in (%%b) do (
for /F "tokens=3" %%d in ('fsutil fsinfo drivetype %%c') do (
if %%d equ Removable (
echo Drive %%c is Removable (USB^)
)
)
)
)
I know this is old but....
#echo off
for /F "usebackq tokens=1,2,3,4 " %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (
if %%l equ 2 (
copy c:\test\big.txt %%i
)
)
This is assuming of course both drives are inserted.
The above code had a flaw which has been attended to in the following code
The code works in XP and gives you the USB drive letters, if no usb device
is connected , it tells you so !
:: SUCCESS # 2:39 AM ON 12 OCT 2013 !!!
:: IMPROVED BY BOBBY GOREJA
#echo off
set usbdrv=
set usb=No
:: Above two lines on 12 Oct 2013
fsutil fsinfo drives >de
type de | find "Drives:" /v >dlist
for /F "tokens=1" %%c in ('type dlist') do (
for /F "tokens=3" %%d in ('fsutil fsinfo drivetype %%c') do (
rem echo Token is %%d
if %%d equ Removable (
echo Drive %%c is Removable (USB^)
set usbletter=%%c
set usb=Yes
echo USB drive letter is %usbletter%
rem set usbdrv = %%c <<< this does NOT work!
rem echo USB1 drive letter is %usbdrv%
)
)
)
del de
del dlist
echo REPEAT:Device at %usbletter%
if "%usb%"=="No" echo No USB Device Connected .
set usb=
#Aacini I don't have a good setup to this case today, so I instead tried finding my USB webcam. I used devmgmt.msc and devcon listclasses to figure out the membership a connected USB camera would have. After a few tests, I arrived at devcon find =Image USB\*. I figured it would be simple enough to do the same for a USB mass storage device, so I tried devcon find =Volume (per listclasses). Unfortunately, this dumps out a GUID which you would then have to map to a drive letter. A cursory glance at this overflow suggests you can do so from the registry using reg query, but it seems at this point that fsutil would be simplest for your case.

Resources