Vbscript扫描驱动器的某个名称,而不是驱动器号并将文件复制到该USB驱动器名称

时间:2014-10-01 01:48:59

标签: vbscript scripting

我正在试图弄清楚如何制作一个vbscript来扫描具有特定名称的USB设备,然后找到一个文件复制到它。

示例而不是扫描驱动器号J,扫描与我要复制到的特定USB设备对应的特定名称。

假设我要找到的USB设备名为TEAM,我希望脚本扫描名称TEAM而不是驱动器号,并将文件复制到其中。我希望这样,因为驱动器号可以更改一次我的名为TEAM的USB设备可能是J字母,然后它可能是E

这样一来,它不必担心驱动器号是否会改变并且总是能够到达我的设备,除非我更改USB设备的名称。

我是编程的新手,我已经创建了一个扫描字母的脚本,但我想更改它,因此它使用USB名称而不是驱动器号。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

向WMI询问所需信息

Option Explicit

Function getDriveLetterFromVolumeName( volumeName )
Dim volumes, volume

    ' Unless we found a matching volume, an empty string will be the returned value
    getDriveLetterFromVolumeName=""

    ' Ask WMI for the list of volumes with the requested label
    Set volumes = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") _ 
                  .ExecQuery("SELECT DriveLetter FROM Win32_Volume WHERE Label='" & volumeName & "'")

    ' If exist an matching volume, get its drive letter
    If volumes.Count > 0 Then 
        For Each volume In volumes 
            getDriveLetterFromVolumeName = volume.DriveLetter
            Exit For
        Next 
    End If

End Function

WScript.Echo getDriveLetterFromVolumeName( "TEAM" )

已修改以适应评论

因此,一旦我们能够确定它是否可用以及驱动器号是什么,唯一剩下的任务就是将源文件复制到目标驱动器

Dim fileToCopy
    fileToCopy = "c:\source\folder\myfile.txt"

Dim usbDrive
    usbDrive = getDriveLetterFromVolumeName( "TEAM" )

    If Not (usbDrive="") Then 
        With WScript.CreateObject("Scripting.FileSystemObject")
            If .FileExists(fileToCopy) Then
                .CopyFile fileToCopy, usbDrive & "\targetFolder\myFile.txt"
            End If
        End With 
    End If