Assigning directory name to a variable in cmd batch

batchcmd.exe

I want to retrieve a file name and assign it to a variable so I can use it further in the script.

set directoryName = dir Docum?nt*
echo %directoryName%

But once I execute the batch file all I get is this.

D:\ >a.bat
D:\ >set directoryName = dir Docum?nt*
D:\ >echo
ECHO is on.

How can I make sure that my variable has been assigned the value i.e. the directory name so I can start writing further script.

my a.bat contains:

set directoryName=dir Docum?nt*
echo %directoryName%

After removing spaces:

D:\Workspace>set directoryName=dir Docum?nt*

D:\Workspace>echo dir Docum?nt*
dir Docum?nt*

I guess, the vairbale has been assigned the whole value along with the command keyword instead of the results. I expect the output to be the directory name i.e. Documentation

Best Answer

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* enter image description here

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

Related Question