SETLOCAL ENABLEDELAYEDEXPANSION causes CD and PUSHD to not persist

前端 未结 4 545
春和景丽
春和景丽 2021-01-18 08:41

I am trying to use setlocal enabledelayedexpansion and cd together in a batch script, which seems to not persist changes back to shell.

The

4条回答
  •  春和景丽
    2021-01-18 08:49

    Saving a string in registry across endlocal. Tested on win7 cmd (skip=2, may differ with different versions of reg.exe)

    :: What: stash string in registry from cmd line, across endlocal barrier
    :: PS. I added %RANDOM% to Windows-NT and Win95 command.com and still using it.
    @echo off
    
    set key="HKCU\Volatile Environment"
    set keyname=stash%RANDOM%
    set keytype=REG_SZ
    
    setlocal ENABLEDELAYEDEXPANSION
    
    ::== Save string
    set data_stash=Hello-%DATE%-%TIME%
    echo Saving=%data_stash% in key=%keyname%
    reg add %key% /v %keyname% /t %keytype% /d "%data_stash%" /f
    
    endlocal
    
    ::== Read string
    echo reg query %key% /v %keyname%
    for /f "tokens=2* skip=2" %%a in ('reg query %key% /v %keyname%') do (
      set data_unstashed=%%b
    )
    echo Read data_unstashed=%data_unstashed% 
    
    ::== Delete stash
    reg delete %key%  /v %keyname% /f  
    

    Edit Stephan another way to save variables beyond endlocal:

    @echo off
    set var1=hello
    set var2=world
    setlocal 
    echo previous: %var1%, %var2%
    set var1=HELLO
    set var2=WORLD
    echo inside:   %var1%, %var2%
    endlocal & set "var1=%var1%" & set "var2=%var2%" 
    echo after:    %var1%, %var2%
    

    The trick is that due to the parsing the variables are expanded before endlocal is effective, but setted after that.
    (sorry for hijacking your answer, but that's also too big for a comment)

提交回复
热议问题