0

I created a simple batch file that copies drop file in specific folder. This my batch script:

rem This will create a BACK-UP DATA Folder in Desktop
rem with a SUB-FOLDER which filename must be the first 5 characters of drop file filename
rem with another folder filename: "COPY" inside (just for another back up)
for %%f in (%1) do (
    set oldName=%%~nf
    set newName=%oldName:~0,5%
    mkdir %HOMEPATH%\Desktop\"BACK-UP DATA"\"%newName%"\
    mkdir %HOMEPATH%\Desktop\"BACK-UP DATA"\"%newName%"\COPY 
    xcopy %%f "%HOMEPATH%\Desktop\BACK-UP DATA\%newName%"
    rem will copy drop file also inside COPY folder
    xcopy %%f "%HOMEPATH%\Desktop\BACK-UP DATA\%newName%\COPY"
    rem open created folder
    start "" "%HOMEPATH%\Desktop\BACK-UP DATA\%newName%\"
    PAUSE
)

This is the output in command prompt...

set oldName="New Text Document"
 set newName=~0,5
  mkdir C:\User\username\Desktop\"BACK-UP DATA"\""\
  mkdir C:\User\username\Desktop\"BACK-UP DATA"\""\COPY
  xcopy "C:\User\username\Desktop\New Text Document.txt" "C:\User\username\Desktop\BACK-UP DATA\"
  xcopy "C:\User\username\Desktop\New Text Document.txt" "C:\User\username\Desktop\BACK-UP DATA\\COPY"
  start "" "C:\User\username\Desktop\BACK-UP DATA\\"
  pause

Why the variable %newName% doesn't work? What's wrong in my script?

1 Answer 1

1

IF you want to declare variables and use this same variables inside for loops or if's you have to use delayed Expansion ex:

SetLocal EnableDelayedExpansion

Also you have to substitute % by !

set "oldName=%%~nf"
set "newName=!oldName:~0,5!"
mkdir "%HOMEPATH%\Desktop\BACK-UP DATA\!newName!\COPY" 
1
  • Edit Note: you don't need the \third line when used \third with the \fourth line, and you never know what characters are in the names, so use "" in the "variables"
    – Io-oI
    Commented Oct 21, 2021 at 1:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .