Batch list usb drives, then copy content

╄→гoц情女王★ 提交于 2019-12-08 05:33:55

问题


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 : 

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27303297/batch-list-usb-drives-then-copy-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!