batch-filedoskey

Evaluate environment variable at runtime with doskey


I'm creating a simple environment setup cmd script and I'm using doskey to setup various aliases and macros. The environment I'm on has various repositories and I wanted to create some macros for quick navigation of popular directories.

I currently have the following:

@echo off
Setlocal EnableDelayedExpansion

set PROJECTS_PATH=%SystemDrive%\Projects

echo. Updating path...

REM Update PATH here 

echo. Setting up macros...

doskey np="%SystemRoot%\System32\notepad.exe" $*
doskey np+="%ProgramFiles(x86)%\Notepad++\notepad++.exe" $*
doskey ..=cd ..
doskey trunk=set PROJECT_ROOT=%PROJECTS_PATH%\Trunk ^& cd "!PROJECT_ROOT!"
doskey trunk2=set PROJECT_ROOT=%PROJECTS_PATH%\Trunk2 ^& cd "!PROJECT_ROOT!"
doskey root=cd "%PROJECT_ROOT%"
doskey tools=cd "%PROJECT_ROOT%\tools"

What I was hoping would happen was that I could use the trunk macro to set the PROJECT_ROOT variable, then navigate to this newly set variable using delayed expansion. Then if I use the trunk2 command it would again reset the PROJECT_ROOT variable and navigate to that location. Finally, with the PROJECT_ROOT variable dynamically set, the root and tools macros could be the same regardless of which project root I'm at.

Unfortunately this doesn't work since it seems that PROJECT_ROOT is evaluated when the macro is created. So the result of running the macro trunk is the variable gets set and then execution of cd "".

Is there any way I can have the macro re-evaluate the PROJECT_ROOT variable in case it has changed?


Solution

  • You don't need delayed expansion to get it working

    @echo off
        setlocal enableextensions disabledelayedexpansion
    
        set "PROJECTS_PATH=%SystemDrive%\Projects"
    
        doskey trunk=cd /d "%PROJECTS_PATH%\trunk" $t set "PROJECT_ROOT=%%cd%%"
        doskey trunk2=cd /d "%PROJECTS_PATH%\trunk2" $t set "PROJECT_ROOT=%%cd%%"
    
        doskey root=cd /d "%%PROJECT_ROOT%%"
        doskey tools=cd /d "%%PROJECT_ROOT%%\tools"
    

    Instead of setting the variable and changing to the target folder, change the active directory and then set the variable.

    The %%var%% inside the batch file will be converted to %var% without expanding the variable while creating the macro. Variable will be expanded when the macro is called.