为什么我得到这个CMD脚本的语法错误?

我试图编写一个简单的CMD脚本来自动生成我的回购。 这里是完整的脚本:

@echo off setlocal goto main :: Functions :buildSubdir pushd %1 for /f %%projectFile in ('dir /b /s project.json') do ( dnu restore "%%projectFile" dnu build "%%projectFile" dnu pack "%%projectFile" ) popd goto :EOF :main :: Check for dnu where dnu > NUL 2>&1 if %ERRORLEVEL% NEQ 0 ( echo dnu wasn't found in your PATH! 1>&2 echo See http://docs.asp.net/en/latest/getting-started/installing-on-windows.html for instructions on installing the DNX toolchain on your PC. 1>&2 exit /b %ERRORLEVEL% ) :: Do the actual work cd %~dp0 call :buildSubdir src call :buildSubdir test 

基本上,它试图在几个select的目录( srctest )中find所有名为project.json的文件,然后对它们执行dnu restorednu builddnu pack

出于某种原因,我似乎得到了一个语法错误,我input一个for /f循环,说%projectFile不被识别的东西。 当我删除@echo off语句并重新运行脚本时,我的terminal完整输出的要点如下。

谁能告诉我为什么发生这种情况,我能做些什么来解决这个问题? 谢谢。


编辑:只是改变它:

 for /f %%p in ('dir /b /s project.json') do ( set projectFile=%%p dnu restore "%projectFile%" dnu build "%projectFile%" dnu pack "%projectFile%" ) 

仍然似乎没有工作,虽然现在的错误信息是不同的。 这是新产出的要点。 (请注意%projectFile%如何设置为空string。)

 for /f "delims=" %%p in ('dir /b /s /ad project.json') do ( dnu restore "%%p" dnu build "%%p" dnu pack "%%p" ) 

目录名称被分配给%%p ,因为这是你正在使用的所有内容,所以你不需要进一步分配它。

delims=确保将整行分配给%%p – 否则,将使用默认分隔符集为%%p分配第一个标记,其实际结果是在第一个空格处截断名称。

看到

 for /? 

从docco的提示。

/addir输出中删除任何目录名称(以防万一有一个目录名称与提供的掩码相匹配 – 虽然可能性很小)

如果您想在%%p操作名称,而不是按原样使用它,则需要使用delayedexpansion或调用另一个例程来执行操作。 The basis of this characteristic is the delayedexpansion陷阱- batch will substitute the *parse-time* value of any The basis of this characteristic is the之前- batch will substitute the *parse-time* value of any %var% it finds in a code-block (parenthesised series of statements) for - batch will substitute the *parse-time* value of any %var% - batch will substitute the *parse-time* value of any ,因此自%projectFile%for循环的开始处是未定义的,批处理将取代它当时的值。

有关文档,请参阅许多与delayedexpansion相关的文章,或阅读其中的少量文档

 set /? 

使用For构造函数,可以在For构造中使用字母作为变量:az和AZ(注意字母区分大小写很重要)。 有很多方法可以使用FOR,我会从这里开始 – http://ss64.com/nt/for_f.html

你也可以FOR /? 根据需要获得帮助。

我想你正在寻找这个:

 @echo off setlocal goto main :: Functions :buildSubdir pushd %1 for /f %%p in ('dir /b /s project.json') do ( dnu restore "%%p" dnu build "%%p" dnu pack "%%p" ) popd goto :EOF :main :: Check for dnu where dnu > NUL 2>&1 if %ERRORLEVEL% NEQ 0 ( echo dnu wasn't found in your PATH! 1>&2 echo See http://docs.asp.net/en/latest/getting-started/installing-on-windows.html for instructions on installing the DNX toolchain on your PC. 1>&2 exit /b %ERRORLEVEL% ) :: Do the actual work cd %~dp0 call :buildSubdir src call :buildSubdir test