【问题标题】:How and Why do Visual Studio and cmd.exe handle batch file differentlyVisual Studio 和 cmd.exe 如何以及为何以不同方式处理批处理文件
【发布时间】:2012-11-15 17:44:52
【问题描述】:

以下是一个程序应该在 VS 中作为预构建事件运行。它可以直接从命令行工作,但不能在 VS 中工作。

@echo off
:: Direct From cmd.exe
:: "G:Google Drive\GitHub\toolset\Site\pre-build.bat" Release "G:Google Drive\GitHub\toolset\Site\Web"
:: From Visual Studio Pre-Build Event
:: "$(SolutionDir)pre-build.bat" $(ConfigurationName) "$(ProjectDir)"

if %1==Release (

    if exist %2 (
        set location=%2
        set dotlessVersion=v1.3.1.0

        :: Compress Less Files
        for /r %location% %%a in (*.less) do (
            "%~dp0..\SharedLibs\dotless\%dotlessVersion%\dotless.Compiler.exe" -m -r "%%a" "%%~da%%~pa%%~na.min.css"
        )

        :: Minify js Files
        for /r %location% %%a in (*.closure.js) do (
            set newFilename=%%a
            call java -jar "%~dp0..\SharedLibs\Closure Compiler\compiler.jar" --js "%%a" --js_output_file "%%newFilename:.closure.js=.min.js%%"
        )
    )
)

【问题讨论】:

  • 为什么不起作用?发生什么了?您在输出窗口中看到了什么?
  • 输出窗口中不显示任何内容。如果我在set location=%2 之后添加echo Value: %location%,则输出为Value: 。 cmd.exe 将变量输出到 echo 中。

标签: visual-studio batch-file cmd pre-build-event


【解决方案1】:

它与visual studio无关,它是标准的批处理初学者错误。
括号中的百分比扩展不符合您的预期。
它在解析完整块时扩展,在执行任何行之前。

所以%location% 被扩展为空,即进入块之前的值。
在 cmd 行它的工作方式相同,但如果你启动批处理两次,它似乎工作,但你只看到正确的值,因为它仍然设置。

如何解决?
不要使用它(百分比扩展),而是使用延迟扩展!

setlocal EnableDelayedExpansion
if %1==Release (

    if exist %2 (
        set location=%2
        echo !location!
        ....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多