是否仅根据标签参考/选择驱动器? (即不是驱动器号)
时间:2020-03-05 18:48:48 来源:igfitidea点击:
我正在尝试指代可能更改其字母的驱动器。我想通过其标签(例如,批处理文件中的MyLabel(v :))来引用它。它可以通过V:\来引用。我想通过MyLabel来引用它。
(这已在Experts Echange上发布了一个月,没有任何答案。让我们看看SO的回答速度有多快)
解决方案
回答
我们可以为此使用WMI查询语言。
请查看http://msdn.microsoft.com/zh-cn/library/aa394592(VS.85).aspx作为示例。
我们正在寻找的信息可用,例如通过Win32_LogicalDisk类的属性VolumeName访问http://msdn.microsoft.com/zh-cn/library/aa394173(VS.85).aspx
SELECT * FROM Win32_LogicalDisk WHERE VolumeName =" MyLabel"`
回答
该bat文件将为我们提供驱动器标签中的驱动器号:
Option Explicit Dim num, args, objWMIService, objItem, colItems set args = WScript.Arguments num = args.Count if num <> 1 then WScript.Echo "Usage: CScript DriveFromLabel.vbs <label>" WScript.Quit 1 end if Set objWMIService = GetObject("winmgmts:\.\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk") For Each objItem in colItems If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then Wscript.Echo objItem.Name End If Next WScript.Quit 0
运行为:
cscript /nologo DriveFromLabel.vbs label
回答
这是一个简单的批处理脚本getdrive.cmd,用于从卷标中查找驱动器号。只需调用" getdrive MyLabel"或者getdrive"我的标签"即可。
@echo off setlocal :: Initial variables set TMPFILE=%~dp0getdrive.tmp set driveletters=abcdefghijklmnopqrstuvwxyz set MatchLabel_res= for /L %%g in (2,1,25) do call :MatchLabel %%g %* if not "%MatchLabel_res%"=="" echo %MatchLabel_res% goto :END :: Function to match a label with a drive letter. :: :: The first parameter is an integer from 1..26 that needs to be :: converted in a letter. It is easier looping on a number :: than looping on letters. :: :: The second parameter is the volume name passed-on to the script :MatchLabel :: result already found, just do nothing :: (necessary because there is no break for for loops) if not "%MatchLabel_res%"=="" goto :eof :: get the proper drive letter call set dl=%%driveletters:~%1,1%% :: strip-off the " in the volume name to be able to add them again further set volname=%2 set volname=%volname:"=% :: get the volume information on that disk vol %dl%: > "%TMPFILE%" 2>&1 :: Drive/Volume does not exist, just quit if not "%ERRORLEVEL%"=="0" goto :eof set found=0 for /F "usebackq tokens=3 delims=:" %%g in (`find /C /I "%volname%" "%TMPFILE%"`) do set found=%%g :: trick to stip any whitespaces set /A found=%found% + 0 if not "%found%"=="0" set MatchLabel_res=%dl%: goto :eof :END if exist "%TMPFILE%" del "%TMPFILE%" endlocal