ebmar
ebmar

Reputation: 11

Batch list usb drives, then copy content

I'm trying to make a batch file that list usb drive (it's usually one connected), then either cd in to the drive or copy the contents from the drive.

I'm trying to to use wmic to list the drive, and I get the drive letter. But I have no idea how to execute the cd command using the information I got from wmic.

wmic command:

wmic volume where "drivetype=2" get driveletter /format:table | findstr : 

Upvotes: 1

Views: 1295

Answers (2)

aschipfl
aschipfl

Reputation: 34899

At first, let us modify your wmic command a bit:

wmic VOLUME WHERE (DriveLetter^>"" AND DriveType=2) GET DriveLetter /VALUE

The DriveLetter>"" portion is intended to remove any volumes that do not have a drive letter.

To use this for other actions, use for /F to get the actual drive letters in a loop:

for /F "tokens=2 delims==" %%V in ('
    wmic VOLUME WHERE ^(DriveLetter^^^>"" AND DriveType^=2^) GET DriveLetter /VALUE
') do for /F "delims=" %%L in ("%%V") do (
    echo current drive:  %%L
    rem change to the root of the drive temporarily:
    pushd %%L\
    rem do your actions here, like `copy` for example (give true destination!):
    copy *.* nul
    rem change back to previous directory:
    popd
)

Several special characters need to be escaped when used within a for /F command; that explains the additional ^ characters.

Actually there are two nested for /F loops where the outer handles the wmic output (see for /? for details). Since wmic outputs additional carriage-returns which might cause trouble, I used a small trick: I nested another for /F loop in the other one, which iterates exactly once per iteration of the outer one.

Instead of the inner sample copy command, you can state also other commands to perform different actions of course.

Upvotes: 0

user4317867
user4317867

Reputation: 2448

Why not use Powershell to list the disks then filter for USB drives and go from there?

Recommended further reading: http://blogs.technet.com/b/heyscriptingguy/archive/2013/08/26/automating-diskpart-with-windows-powershell-part-1.aspx

Powershell script: https://gallery.technet.microsoft.com/DiskPartexe-Powershell-0f7a1bab

Try out some of those commands and reply back with what you want to do and your Powershell attempts and we'll help refine that.

Upvotes: 1

Related Questions