Home > Back-end >  Finding a drive name...not the drive letter...with batch file
Finding a drive name...not the drive letter...with batch file

Time:12-24

I have a requirement in a batch file to copy archived files to a specific drive name...not letter. I need to support the drive having different drive letters assigned as it is installed, removed, and moved around. I want to be able to find the drive by its unique name, so that I can then reference the appropriate drive letter for that drive.

This is the closest code I could find on the forum:

for /f "usebackq tokens=2 delims=:=" %%a in (wmic logicaldisk where VolumeName^="BACKUP2" get caption /value) do set drive=%%a: if "%drive%"=="" ( echo not inserted ) else (cls echo inserted as %drive% )

Which produces "inserted as "BACKUPS2" GET caption /value:" as the output. I was expecting the return of only the drive letter.

In doing my due diligence, I looked at /? for wmic which listed LOGICALDISK as an alias. The wmic help directed me to "switch-alias /?" for help on the alias, but both "LOGICALDISK /?" and "switch-LOGICALDISK /?' report that neither is recognized as an internal or external command....yada, yada.

I note that wmic /? says that wmic is depreciated. Don't know if that affects documentation being available. I also note that the code listed above to find the drive name..not letter...is pretty old.

I'm stuck. If anyone can pull my head out, or suggest an alternate solution, I'd appreciate the effort.

CodePudding user response:

Wouldn’t it be easier to use the complete UNC Path \\server\volume instead of searching for the drive letter?

CodePudding user response:

Luckily I play a Brain Scientist on TV.

FOR /F "skip=2 tokens=2 delims=," %%G IN ('wmic logicaldisk where volumename^="BACKUP2" get caption /format:csv') DO SET "drive=%%G"

CodePudding user response:

If you're unsure about using the deprected WMIC.exe utility, there are others you can use, and those may be just a little bit quicker too.

You could try this idea:

@SetLocal EnableExtensions EnableDelayedExpansion
@For /L %%G In (68, 1, 90) Do @(%SystemRoot%\System32\cmd.exe /D /C Exit /B %%G
    Vol !=ExitCodeAscii!: 2>NUL | %SystemRoot%\System32\findstr.exe /RIC:" BACKUP2$" 1>NUL && Copy /Y "C:\MyDir\*" !=ExitCodeAscii!:\)

Obviously you'd change "C:\MyDir\*" to your actual source file glob and add further branches the the destination root directory !=ExitCodeAscii!:\ as needed.

  • Related