Batch to choose drive letter

Asked

Viewed 571 times

4

I’m creating a menu for deploy imaging via winpe. Inside this I run some commands and apply to files that are stored on an external hard drive.

I even managed to make one if exist c:\IMG GOTO and continue with the script, but as the letters may vary greatly, the script gets a lot.

Is there any way to assign a value to a variable through a condition, something like:

If exist C:\IMG então VAR=C

And then apply the commands as being VAR:\IMG\image.wim

I would like the variable in case it matches the drive letter containing the folder IMG.

  • You want to go through all the drives and check if there is IMG folder at the root?

2 answers

2

Use the command SET to define a variable and with EXIST you check if a file or folder exists.

SET "LETRA="                 :: Declara a variável que vai receber a letra do drive

if exist C:\ (               :: Se existir
 SET LETRA=C:\               :: Coloca a letra do drive na variável LETRA
) else (                     :: Se não encontrar
 echo Arquivo nao encontrado
 PAUSE
 EXIT /B
)
echo %LETRA%IMG\image.wim    :: Exibe o caminho da imagem se existir

If you often need to check whether a file/directory is existing, automating this process in a function can save you some lines of code:

SET "LETRA="                 :: Declara a variável que vai receber a letra do drive
call :ElegerDrive c:\        :: Chama "ElegerDrive" com um argumento, no caso c:\

:ElegerDrive
IF EXIST %~1 (               :: Se o arquivo ou pasta existir
   SET LETRA=%~1             :: Atribui a variável LETRA o argumento
   GOTO :FIM                
) ELSE (
   echo O drive %~1 nao foi encontrado.
   PAUSE
   EXIT /B
)
:Fim
echo %LETRA%IMG\image.wim
PAUSE

0

inserir a descrição da imagem aqui

You can use the mountvol to obtain the drivers mounted on the system already moving to a variable and use it in a looping for to verify the existence of the folder in each driver mounted via findstr, and, if positive, specify its variable....

@echo off & setlocal enabledelayedexpansion & cls & echo/

for /f "tokens=*delims= " %%f in ('mountvol^|find /i ":\"')do set _drv=!_drv!, %%f
echo/ Procurando nos drivers: !_drv:~1! & for %%f in (!_drv:~1!)do 2>nul dir %%fIMG /ad|^
findstr /il %%fIMG>nul && echo/ && set "_IMG=%%fIMG" && echo/ Localizado em: !_IMG!

Or a little simpler...


inserir a descrição da imagem aqui


@echo off & setlocal enabledelayedexpansion & cls & echo/

for /f "tokens=*delims= " %%f in ('mountvol^|find /i ":\"')do 2>nul dir %%fIMG /ad |^
findstr /il %%fIMG>nul && (echo/ & set "_IMG=%%fIMG" & echo/Localizado: !_IMG! & echo/)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.