Super new to batch files and programming in general so any help is appriciated; I'm trying to copy, and rename a file based on user input, then open the new file. My issue is, If there is a duplicate, I want it to re-prompt the user for a different name. Right now I have:
SET /P "dname=Type new sheet name, then press Enter:"
COPY "O:\master.xlsx" "O:\%dname%.xlsx" /V /-Y
START /D "O:" %dname%.xlsx
And this works for copying and renaming, but if there is a duplicate, I get the prompt 'do you want to copy Y/N' but if I say no, it doesn't ask for a different name. Thank you!
Edit 1: I now have this:
SET /P "dname=Type sheet name, then press Enter:"
IF EXIST "O:\%dname%.xlsx" (
:RETRY
SET /P "dname=Error! There is already a file named %dname%. Please choose a new unique name:"
IF EXIST "O:\%dname%.xlsx" (
GOTO :RETRY
ELSE GOTO :COPY
)
) ELSE GOTO :COPY
:COPY
COPY "O:\master.xlsx" "O:\%dname%.xlsx" /V /-Y
And it seems to work reliably. Is there a better way to streamline/optimize this with a loop? Or is that good enough?
This is how I would do it:
@echo off
setlocal
set "oldname=master"
:loop
set "newname=%oldname%"
set /p "newname=New Name: "
if exist "%newname%.xlsx" (
echo %newname%.xlsx already exists. Chose another name.
goto :loop
)
COPY "%oldname%.xlsx" "%newname%.xlsx"