'loop through a folder with special characters in the folder name
I'm trying to write a batch file to move files from a folder into another folder. The folder has a special character in the name. I can't change that name.
Here is my script
set "MM=%Date:~4,2%"
set "DD=%Date:~7,2%"
set "thisDate=%MM%%DD%"
set baseDir="T:\R ^& D files received"
set backupDir=%baseDir%\2022\%thisDate%
if not exist "%backupDir%\NUL" mkdir "%backupDir%"
for %%f in ("%baseDir%\*.pdf") do (
echo %%f
move %%f "%backupDir%\%%f")
This is not working. I get
R
&
D
files
received\*.pdf
No file is moved. Any idea or help is appreciated.
Solution 1:[1]
@ECHO OFF
SETLOCAL
SET "thisdate=0419"
set "baseDir=U:\R & D files received"
set "backupDir=%baseDir%\2022\%thisDate%"
if not exist "%backupDir%\NUL" mkdir "%backupDir%"
for %%f in ("%baseDir%\*.pdf") do (
echo "%%f"
move "%%f" "%backupDir%\%%~nxf" >nul
)
DIR /s "%basedir%"
GOTO :EOF
Intriguingly. you've used the set "var=value" format for setting thisdate but not for the directory names. I've used a constant for thisdate as I use a YYYYMMDD date format.
Also, my test drive is U:, not T:.
Tips : Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, space or quotes - build pathnames from the elements - counterintuitively, it is likely to make the process easier.
Your for %%f resolved to for %%f in (""T:\R ^& D files received"\*.pdf") do ( hence the strange result.
Note that %%f contains the full pathname to the .pdf files - which includes spaces. Hence you need to "quote the sourcefile name" and use just the name and extension of that file (%%~nxf) concatenated onto the backupdirectoryname string with separator - all of which again contains a space and hence needs to be quoted.
>nul appended to suppress 1 file(s) moved messages.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Magoo |
