Windows – How to get the current directory name in a windows command prompt inside of FOR loop

batchbatch-renamecmd.execommand linewindows

I'm using Win-10 64-bit.

Given the following directory structure on my windows machine…

c:\tmp\Logs_UAT\
'-> folder1
|   '-> test.txt
'-> folder2
    '-> test.txt

…I'm trying to rename all files in each directory by prefixing them with the directory name, to have:

c:\tmp\Logs_UAT\
'-> folder1
|   '-> folder1_test.txt
'-> folder2
    '-> folder2_test.txt

In order to achieve this, I'm looping recursively through files in the %basedir% using FOR and in each directory I'm getting a current directory name using the inner FOR "loop", and then doing a rename. However, current directory is usually not derived correctly. Here's the .bat file which allows to reproduce the issue:

@echo off

set basedir=c:\tmp\Logs_UAT

for /R %basedir% %%I in (*) DO (
cd %%~pI

for %%G in (.) do echo %%~nxG> temp.temp
set /P curdir=<temp.temp
del /f temp.temp

echo.
echo -------------------
echo %%I
dir
echo %curdir%
echo -------------------
)

It outputs the same value for %curdir% for both files:

C:\tmp>test.bat

-------------------
c:\tmp\Logs_UAT\folder1\test.txt
 Datenträger in Laufwerk C: ist OSDisk
 Volumeseriennummer: D280-2DC0

 Verzeichnis von C:\tmp\Logs_UAT\folder1

06.05.2020  19:29    <DIR>          .
06.05.2020  19:29    <DIR>          ..
06.05.2020  19:02                 0 test.txt
               1 Datei(en),              0 Bytes
               2 Verzeichnis(se), 291.684.151.296 Bytes frei
folder2
-------------------
.
-------------------
c:\tmp\Logs_UAT\folder2\test.txt
 Datenträger in Laufwerk C: ist OSDisk
 Volumeseriennummer: D280-2DC0

 Verzeichnis von C:\tmp\Logs_UAT\folder2

06.05.2020  19:29    <DIR>          .
06.05.2020  19:29    <DIR>          ..
06.05.2020  19:02                 0 test.txt
               1 Datei(en),              0 Bytes
               2 Verzeichnis(se), 291.684.151.296 Bytes frei
folder2
-------------------

C:\tmp\Logs_UAT\folder2>

I tried:

  1. Fresh console window
  2. Console and batch file
  3. Sometimes I'm getting the first folder name and sometimes second
  4. Lots of search on the internet

I'd prefer to stick to standard windows utilities as I have to distribute the script to other users which might not have the extra software.

How do I get the current directory name in a windows command prompt inside of FOR loop?

Best Answer

Indeed DelayedExpansion helped, thanks DavidPostill. Here's the working script:

@echo off
SETLOCAL EnableDelayedExpansion
set basedir=c:\tmp\Logs_UAT

for /R %basedir% %%I in (*) DO (
cd %%~pI

for %%G in (.) do echo %%~nxG> temp.temp
set /P curdir=<temp.temp
del /f temp.temp

echo !curdir!
)

endlocal
Related Question