Search code examples
batch-filebatch-rename

Rename Batch File Has To Be In Same Folder


For some reason my code below only works if the batch file is in the same folder as the files to be renamed even though i've specified the path. When the batch file is in a different folder I receive an error saying the file can't be found. Any input on this?

@echo off&setlocal
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
for /f "delims=" %%a in ('dir C:\Users\%username%\Downloads\Export_*.csv /b /a-d /o-d') do (
    set "fname=%%~a"
    set /a counter+=1
    SETLOCAL ENABLEDELAYEDEXPANSION
    call set "nname=%%name!counter!%%"
    ren "!fname!" "!nname!%%~xa"
    endlocal
)

Solution

  • just add a working path:

    @echo off&setlocal
    set "workingpath=%userprofile%\Downloads"
    set "name1=Bart"
    set "name2=Carl"
    set "name3=Judy"
    for /f "delims=" %%a in ('dir "%workingpath%\Export_*.csv" /b /a-d /o-d') do (
        set "fname=%%~a"
        set /a counter+=1
        SETLOCAL ENABLEDELAYEDEXPANSION
        call set "nname=%%name!counter!%%"
        ren "%workingpath%\!fname!" "!nname!%%~xa"
        endlocal
    )