Home > database >  Accessing files from a path in batch scripts
Accessing files from a path in batch scripts

Time:10-13

I have a batch script, where I want to list out the folders from a path. I am executing the batch script from a different location.

I have the script as below, but it fails:

@echo off
set PATH = C:\Users\XXX\Downloads\CmdLine;
for /d %%D in (%PATH%) do (
    echo %%~nxD 
    echo.
)

It prints out :

\Common was unexpected at this time

I want the list of folder names to be printed. Any suggestions?

PS: A starter in batch scripting

CodePudding user response:

There are three main issues with your script.

First and foremost, %PATH% is already a system variable, and it tells Windows where important things are located on your system. Please do not change its value unless you know what you're doing.

Second, variable names in batch are allowed to have spaces in them, so you've actually created a variable called %PATH % and given it the value C:\Users\XXX\Downloads\CmdLine; (note the leading space).

Third, for /D only iterates over folders if the set contains a wildcard.


If you correct the three issues, your code will look like this:

@echo off
set "parent_dir=%USERPROFILE%\Downloads\CmdLine"
for /d %%D in (%parent_dir%\*) do (
    echo %%~nxD 
    echo.
)

Other optional changes are putting quotes around the set statement to prevent hidden trailing spaces and using %USERPROFILE% instead of C:\Users\xxxx to make the script more portable.

  • Related