windows cmd get USB drive letter automatically without batch file - windows

I have a PC in which I insert a USB Drive and execute a batch script, but the USB Drive interacts with the computer, so I need to know in which Drive Letter it is mounted.
I tried this
for /f "tokens=2,3 delims= " %%A in ('WMIC logicaldisk where "DriveType=2" get /value | find "Caption="') do (
set drive=%%A
)
But I get an error stating Did not expect %%A at this moment.
I know this works
#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 (
echo %%i is a USB drive.
)
)
But it implies having to save it in a .bat file, and I don't want to do that.
Ideally, what I want to do is to be able to switch to the USB Drive without needing to launch it from a .bat file, so this command should allow me to get the Drive Letter. Afterwards, the script continues.

Thanks to the #aschipfl I managed to find out the right command:
for /F "usebackq tokens=1,2,3,4 " %i in (`WMIC logicaldisk where "DriveType=2" get /value ^| find "Caption="`) do (set drive=%i)
set drive=%drive:~8,9%
And now %drive% is the letter in which the drive is mounted. If there are more than one mounted letters, it will be the last one.

Related

how can I program the volume serial number into a variable for a batch file?

This Win7 batch file code retrieves the Serial Numbers for all drives on the computer and displays them in a command window, however
I am unable to isolate just the drive %~d0 from which the code is running and capture the volumeserialnumber into a %variable_%.
rem -----------Test volumeSerialNumber.BAT------------------
#echo off
wmic logicaldisk where drivetype=3 get volumeserialnumber
pause
for /F "skip=1 delims=" %%j in ("wmic logicaldisk where deviceid = '%~d0' get volumeserialnumber") do (
set SERIAL=%%j
goto :DONE
)
:DONE
echo SERIAL=%SERIAL%
echo %SERIAL%
pause
if "%SERIAL%"=="The Serial Number of Drive C" (
echo "Success!"
)
It looks like you just needed to change some single and double quotes.
Try:
For /F "Skip=1 Delims=" %%j In ('WMIC LogicalDisk Where "DeviceID='%~d0'" Get VolumeSerialNumber') Do ...

free disk space via cmd batch file

need a cmd command to use it in batch file to get free disk space on C drive after and before removing some folders in .txt format or need to know a space for specific folders and also export it in .txt folder
Since cmd.exe's set /A-math is limited to signed 32bit integers, you could get into trouble calculating free space on an empty 4TB drive. A way around is to use PowerShell for the calcuation.
#Echo off
For /f "tokens=2 delims==" %%A in (
'wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value'
) Do Set FS1=%%A
:: Delete something
Del /F /A /Q /S "%tmp%\*" >Nul 2>&1
For /f "tokens=2 delims==" %%A in (
'wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value'
) Do Set FS2=%%A
set FS
:: Let PowerShell do the calculating
powershell.exe "\"{0,10} GB freed\" -f [math]::round(($env:FS2-$env:FS1)/(1GB),2)"
Sample output:
FS1=87454994432
FS2=85188575232
2,11 GB freed

else into a loop detect drive

I need to include an "else echo No USB detect" into this .bat (not add "if %%l NEQ 2")
for /F "usebackq tokens=1,2,3,4 " %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (
if %%l equ 2 (
echo USB detect in %%i
)
)
In simple words: if USB detected, then "echo OK". But if it does not detect the USB, then "echo No" and exit. Thanks
Solved by Tim
Important Note:
This script (by Stephan) in my opinion, is much higher to detect drives
#echo off
setlocal enabledelayedexpansion
REM get removable loaded drives:
for /f %%a in ('"wmic logicaldisk where (drivetype=2 and size is not null) get caption,size 2>nul|find ":""') do set usb=!usb! %%a
REM show a overview:
if defined usb (echo removable drives found in: %usb%) else echo no removable drive found
REM show them one-by-one:
for %%a in (%usb%) do echo removable drive found in %%a
wmic has more power than you think:
#echo off
setlocal enabledelayedexpansion
REM get removable loaded drives:
for /f %%a in ('"wmic logicaldisk where (drivetype=2 and size is not null) get caption,size 2>nul|find ":""') do set usb=!usb! %%a
REM show a overview:
if defined usb (echo removable drives found in: %usb%) else echo no removable drive found
REM show them one-by-one:
for %%a in (%usb%) do echo removable drive found in %%a
Your question was adding an ELSE clause to your IF statement. I recommended adding ELSE between your two close parenthesis. This code does exactly that:
#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 (echo USB detect in %%i) ELSE (echo No USB Detect)
)
This is my output with no USB drives plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
No USB Detect
No USB Detect
No USB Detect
This is my output with a thumbdrive plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
No USB Detect
No USB Detect
USB detect in D:
No USB Detect
Here is my result of the WMIC command you used:
C:\Users\tim\Documents\Scripting Tools>wmic logicaldisk get caption,description,drivetype
Caption Description DriveType
C: Local Fixed Disk 3
D: Removable Disk 2
You might notice it echos No USB Detect 3 times. This is correct because the FOR loop you have constructed loops through each line of output. WMIC outouts one line with the headers (Caption, Description, and DriveType), a line for each drive (and C: is not DriveType 2), and then a blank line.
Your last line, In simple words: if USB detected, then "echo OK". But if it does not detect the USB, then "echo No" and exit. Seems to imply that you only want a simple Installed/Not Installed, not a yes/no for each line of output from your WMIC query. If that is the case, you don't need (or want) an ELSE. Try this instead:
#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 (
echo USB detect in %%i
goto RestOfBatch
)
)
echo USB not detected
:RestOfBatch
Without a usb drive plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
USB not detected
And with a usb drive plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
USB detect in D:
If neither of these produce the desired result, please define your issue more clearly. http://ss64.com/nt/ has a comprehensive list of batch commands and their syntax. You can also add /? to the end of a command to get examples. EG: IF /?
This code works for me. Save it to test.bat and run from open Cmd Prompt. It prints only disk related info, no garbage:
#echo off
setlocal enabledelayedexpansion
for /F "usebackq tokens=* skip=1" %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (set "dsk=%%i"
if "!dsk:~-12,1!" equ "2" (echo USB disk detected in !dsk:~0,2!
) else if "!dsk:~-12,1!" gtr "2" (echo No USB disk detected in !dsk:~0,2!) )
exit /b

Detecting Removable drive letter in CMD

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 a FOR 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's WMIC and FOR /F: A fix for the trailing <CR> problem
#echo OFF
SETLOCAL enableextensions
set "USBCounter=0"
for /F "tokens=2 delims==" %%G in ('
WMIC logicaldisk where "DriveType=2" get DeviceID /value 2^>NUL ^| find "="
') do for /F "tokens=*" %%i in ("%%G") do (
set /A "USBCounter+=1"
echo %%i
rem your stuff here
)
echo USBCounter=%USBCounter%
rem more your stuff here
ENDLOCAL
goto :eof
Here the for loops are
%%G to retrieve the DeviceID value;
%%i to remove the ending carriage return in the value returned: wmic behaviour: each output line ends with 0x0D0D0A (CR+CR+LF) instead of common 0x0D0A (CR+LF).
One could use Caption or Name instead of DeviceID:
==>WMIC logicaldisk where "DriveType=2" get /value | find ":"
Caption=F:
DeviceID=F:
Name=F:
Note there could be no or more disks present having DriveType=2:
==>WMIC logicaldisk where "DriveType=2" get /value | find ":"
No Instance(s) Available.
==>WMIC logicaldisk where "DriveType=2" list brief
DeviceID DriveType FreeSpace ProviderName Size VolumeName
F: 2 2625454080 3918512128 HOMER
G: 2 999600128 1029734400 LOEWE
Script output for no, then one and then two USB drive(s), respectively:
==>D:\bat\SO\31356732.bat
USBCounter=0
==>D:\bat\SO\31356732.bat
F:
USBCounter=1
==>D:\bat\SO\31356732.bat
F:
G:
USBCounter=2
==>

Translate Hard drive letter into the corresponding Device ID (or viceversa)

I need to Identify the drive letter of a Manufacturer ID of a hard drive device (or maybe viceversa thing I could do it too).
The command to retrieve the manufacturer IDs:
WMIC.exe DiskDrive Get /Format:List
Example Output (splitted and with HTML entities formatted):
PNPDeviceID=DISK&VEN_WDC_WD10&PROD_02FAEX-00Z3A0
The command to retrieve the drive letters:
WMIC.exe Volume Get /Format:List
Example Output:
DriveLetter=C:
The problem is that I can't find any useful property that I could associate from both outputs to make a query, I mean I don't know what to do with the manufacturer IDs to search the drive letter of each ID, I can't see any way to identify the drive letter of the ID.
So at the moment that I get the DeviceID DISK&VEN_WDC_WD10&PROD_02FAEX-00Z3A0 I need to translate it to the equivalent driveLetter, which is C:, that's all.
I've tried using WMIC tool 'cause I don't know how to associate this info using native commandline tools provided in Windows, but really is not full necessary for me to accomplis this task accesing to WMI Classes, I could accept a solution using other presintalled tools in Windows (maybe BCDedit?), or a solution in VBScript language should be accepted too, but for environment circunstances I can't do this task in any other languages (included native PowerShell) and also not using 3rd party tools like Devcon utility provided by Microsoft.
The reason why I need that is to finish this Script which should retrieve and exclude the DeviceID of the DriveLetter C::
#Echo OFF & REM Mode con cols=150 lines=50
:: Exclude this drive during the process.
Set "ExcludedDrive=C:"
:: This variable should be set later,
:: Stores the device ID of the drive letter excluded above.
Set "ExcludedID="
REM ************
REM PSEUDO CODE:
REM ************
REM
REM To get Volume Information:
REM WMIC.exe Volume Get /Format:List
REM WMIC.exe Volume Where 'DriveLetter="C:"' Get /Format:CSV
REM
REM To get DiskDrive Information:
REM WMIC.exe DiskDrive Get /Format:List
REM
REM :: Identify the drive letter of each DeviceID to add exclusions
REM For Each %%DriveLetter in %ExcludedDrive% do (
REM
REM :: Retrieve an WMIC Result
REM Set WMIC_Query_Result=¿?
REM Set WMIC_Query_Result_DriveLetter=¿?
REM Set WMIC_Query_Result_DeviceID=¿?
REM
REM If %WMIC_Query_Result_DriveLetter% EQU %%DriveLetter (
REM Set "ExcludedID=%WMIC_Query_Result_DeviceID%"
REM )
REM )
REM
REM ******************
REM END OF PSEUDO CODE
REM ******************
For /F "Tokens=* Delims=" %%a In (
'REG.exe Query "HKLM\SYSTEM\CurrentControlSet\Enum\SCSI" ^| Find /I "Disk&"'
) Do (
Echo "%%a" | Find /I "%ExcludedID%" || (
For /F "Tokens=* Delims=" %%b In ('REG.exe Query "%%~a"') Do (
Reg.exe ADD "%%b\Device Parameters\Disk" /V "UserWriteCacheSetting" /T "REG_DWORD" /D "0x00000000" /F 1>NUL
)
)
)
Pause&Exit
Does
diskpart /s diskpart.script
with two lines in the script
select disk 0
detail disk
help?
Solution to get the Device ID of the Hard drive that stores the System (C:)
#Echo OFF & Setlocal EnableDelayedExpansion
(
REM Diskpart Script to get details about the System's Hard Drive.
Echo Select Disk=System
Echo Detail Disk
) > "%TEMP%\Diskpart.tmp"
For /F "Tokens=*" %%# in (
'Diskpart /S "%TEMP%\Diskpart.tmp" ^| Find /I "Disk Device"'
) Do (
For /F "Tokens=1,2,* Delims=\ " %%a in (
'WMIC.exe DiskDrive Where Model^="%%#" Get PNPDeviceID /Format:CSV ^| Find /I "&"'
) Do (
Set "DeviceID=%%b"
Set "DeviceID=!DeviceID:&=&!"
)
)
Echo "!DeviceID!"
Pause&Exit /B 0

Resources