不知道是年龄大了还是缺乏练习。无论哪种方式,我都无法解决这个问题。我正在尝试设置一个子例程,但由于字符串 3 和 4 中的空格,我传递的字符串被分割。
SET SubA=String1,String2,String 3,String 4
FOR %%A IN (%SubA%) DO MD "%%A"
我尝试在字符串两边加上括号 <> 括号就像微软所说的那样使用。我也尝试过下面的这一行,但没有成功。
setlocal enableDelayedExpansion
For /F "tokens=* delims=" %%A IN (%Var%) DO MD "%%A"
此外,如果可能的话,我希望我可以制作一个列表,可能带有一个数组。就像在 Power shell 中一样,我可以做到这一点。我确实需要保留在同一个批处理文件中,以便用户可以编辑列表。我知道我可以使用插入符号,但我为客户做得越简单越好。
$Folders (
String1
String2
String 3
String 4
)
最佳答案
最简单的不需要技巧的纯批处理文件解决方案是使用for
枚举空格分隔标记的能力 .
为了使其按预期工作,本身包含空格的标记必须用双引号引起来:
@echo off & setlocal
:: Space-separated list of folder names, with names that contains
:: spaces themselves double-quoted.
SET SubA=String1 String2 "String 3" "String 4"
:: Loop over the list elements and create a directory for each.
FOR %%A IN (%SubA%) DO MD %%A
如Compo's helpful answer意味着,您实际上可以将此列表传递给
的单个调用
MD
:MD %SubA%
不幸的是,据我所知,批处理文件没有提供一种以每行一项格式定义列表的便捷方法。
但是,您可以通过外部文件提供名称列表,每个名称都在自己的行上(不需要双引号),然后可以用 for/f
解析;例如:
@echo off & setlocal
:: Determine the full path of the file "names.txt"
:: located in the same folder as this batch file.
set "nameList=%~dp0names.txt"
:: Loop over all names in the file and call `md` with each.
for /f "usebackq delims=" %%n in ("%nameList%") do md "%%n"
输入文件 names.txt
将包含如下内容:
String1
String2
String 3
String 4
关于arrays - 使用 cmd 创建一组文件夹 - 设置带有空格的循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66847497/