我需要一些关于批处理文件的建议 If exists then followed with a loop

I need a bit of advice on a Batch file If exists then followed with a loop

我正在尝试创建一个批处理文件,将文件从一个文件夹复制到它创建的新文件夹,(mkdir "new folder") 并重命名该文件夹 1。如果文件夹 1 已经存在,则将其命名为文件夹 2。这将通过将 1 添加到文件夹名称来循环,直到该文件夹​​不存在,然后将文件复制到该文件夹​​。

到目前为止,这是我的代码,我已经在该网站上搜索了一些方向,但没有找到任何专门这样做的东西。任何帮助将不胜感激。

程序中设置了我需要帮助的地方::评论

@ECHO OFF
cd c:\
set a=1
mkdir C:\"New folder"
ren "C:\New folder" "%a%"

:: if the folder already exists then

set /a "a=%a%+1"
ren "C:\New folder" "%a%"

:: I need this to loop till the folder does not already exist and then can be renamed.
:: Then I need to files located in "c:\folder_to_copy" to copy into the newly named folder

robocopy "c:\folder_to_copy" "c:\%a%"

这很简单:

set i=0
:loop
set /a i+=1
md "%i%" 2>nul || goto :loop
echo created %i%

|| 相当于 "if previous command failed (could not create the folder) then"

PS: 确保有写入权限 - 否则会变成死循环(无法创建文件夹)

或根据您的用例进行调整:检查文件夹是否存在,直到找到不存在的文件夹:

set i=0
:loop
set /a i+=1
if exist "%i%\" goto :loop
ren "c:\new folder" "%i%"