Question

The following is a program is supposed to run as a pre-build event in VS. It works from the directly from command line but not in 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%%"
        )
    )
)
Was it helpful?

Solution

It has nothing to do with visual studio, it's the standard batch beginner bug.
Percent expansion doesn't work in parenthesis as you expected.
It expands when the complete block is parsed, before any of the lines is executed.

So %location% is expanded to nothing, the value before it enters the block.
At the cmd line it works the same way, BUT if you start the batch two times, it seems that it works, but you only see the correct value, as it is still set.

How to solve it?
Don't use it (the percent expansion), use delayed expansion instead!

setlocal EnableDelayedExpansion
if %1==Release (

    if exist %2 (
        set location=%2
        echo !location!
        ....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top