Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in CMD... how to loop A to Z (for drive letters)

How can I get drive the valid drive letters from A to Z with the "for loop" in windows command line (cmd.exe)?

Example, list all files in a drive root folder, should be something like (conceptual):

for %f in (A..Z) do dir %f:\

or aproximating existing functionality:

for /L in (A, Z, 1) do echo %f:\

like image 938
ZEE Avatar asked Jan 28 '14 16:01

ZEE


2 Answers

Close, but it's more like this.

for %%p in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if not exist %%p:\nul set FREEDRIVELETTER=%%p

EDIT: Here is a powershell way, not sure if off-topic for your needs

Loops the Upper Case Alphabet

65..90 | foreach {[char]$_;Write-Host "Do Something"}

or Lower Case Alphabet

97..122 | foreach {[char]$_;Write-Host "Do Something"}

Maybe this will work from a batch file.

@ECHO OFF
start /b /wait powershell.exe "97..122 | foreach {$a=[char]$_ ;dir $a:\}"
PAUSE
like image 70
Knuckle-Dragger Avatar answered Sep 19 '22 03:09

Knuckle-Dragger


To loop through all drive letters without explicitly stating them you could use forfiles (which is delivered with all Windows versions past Vista, I believe) and its capability to expand hex. codes 0xHH, together with exit to set the exit code and the hidden variable =ExitCode to convert the exit code to a hexadecimal value, like in this example code:

@echo off
for /L %%C in (0x41,1,0x5A) do (
    cmd /C exit %%C
    for /F %%D in ('
        forfiles /P "%~dp0." /M "%~nx0" /C "cmd /C echo 0x%%=ExitCode:~-2%%"
    ') do echo %%D:\
)

This is quite slow though, because there are several cmd instances opened and closed.


To loop through all available drives, including network drives and also such established by subst, you could use the following code, based on wmic:

for /F "skip=1" %%C in ('wmic LogicalDisk get DeviceID') do for /F %%D in ("%%C") do echo %%D\

To loop through all local drives, you could use the following code, again based on wmic:

for /F "skip=1" %%C in ('wmic Volume where "DriveLetter is not Null" get DriveLetter') do for /F %%D in ("%%C") do echo %%D\

To loop through all local drives, but based on mountvol, you could use the following code instead:

for /F %%C in ('mountvol ^| find ":\"') do echo %%C

Finally, for the sake of completeness, to loop through all drives that have been established by subst, use the this code:

for /F "delims=\" %%C in ('subst') do echo %%C\
like image 29
aschipfl Avatar answered Sep 17 '22 03:09

aschipfl