Assigning directory name to a variable in cmd batch
If what you want is to set the directory name which matches Docum?nt*
, then what you need is:
for /d %%d in (Docum?nt*) do set directoryName="%%d"
If more than one directory matches the mask, then you will get only one of the matches. If you need the variable to hold a list of the matching directories, then you will need to use for /f
.
No spaces.
If you have to use space in names, put them under this format:
set directoryName = "dir Docum?nt*"
It's either "" or no spaces.
You have white space before and after the equal sign of the setting of the variable, just remove it and use the method below for example.
@ECHO ON
set directoryName=dir Docum?nt*
echo %directoryName%
Wrong
set directoryName = dir Docum?nt*
Correct
set directoryName=dir Docum?nt*
Implicit FOR Loop
FOR /F "TOKENS=*" %%F IN ('DIR /B /AD "Docum?nt*"') DO SET directoryName=%%~F
Recursive FOR Loop
FOR /F "TOKENS=*" %%F IN ('DIR /B /AD /S "Docum?nt*"') DO SET directoryName=%%~F
Further Resources
- FOR /F