保存未知(用户)文件/目录数的批处理脚本

时间:2015-12-08 23:48:14

标签: batch-file windows-7 backup

我试图做一个批处理脚本,它会对文件/控制器进行备份,这个路径是由用户给出的。问题是我需要让用户决定路径数量他想进入(可以超过10),然后在新目录中制作所有文件/目录的副本。到目前为止,我只做了一个路径作为参数:

SET /P numuser=How many paths?
SET /P pathh=Enter the path
SET "foldname=sav-%DATE%-%TIME:~0,8% 
SET "foldname=%foldname::=-%
echo foldname=%foldname%
mkdir "%foldname%"
cd "%foldname%"
xcopy "%pathh%" "%cd%"
pause

我不太确定如何能够在不同的变量中存储所有不同的路径,考虑到使用决定路径的数量。所以我不能初始化变量,如" SET path1 =" " SET path2 ="等等。因为我无法知道我需要的路径数量。我想我需要一个循环:

FOR %%c IN(numuser) DO
SET /P path1=enter the path
xcopy "%path1%" "%cd%"

但是我又遇到了路径变量名称的问题。我需要增加并创建新变量作为循环进度。我不知道该怎么做

谢谢!

1 个答案:

答案 0 :(得分:0)

允许“将所有不同路径存储在不同变量中”的概念的技术术语是array。下面的批处理文件显示如何使用数组来解决此问题。请注意,用户在按Enter键之前更容易提供多个路径,而不是事先计算所需路径的数量:

@echo off
setlocal EnableDelayedExpansion

rem Get the paths from user and store them in "path" array
set num=0
:nextPath
   set "input="
   set /P "input=Enter next path: "
   if not defined input goto endPaths
   set /A num+=1
   set "path[%num%]=%input%"
goto nextPath
:endPaths

rem Process the stored paths
for /L %%i in (1,1,%num%) do (
   echo Processing: "!path[%%i]!"
)

有关批处理文件中阵列管理的进一步说明,请参阅this post