通過endlocal在註冊表中保存字符串。在win7 cmd上測試(skip = 2,可能與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
編輯斯蒂芬 另一種方式來保存變量超出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%
的訣竅是,由於解析變量擴大之前endlocal
是有效的,但set
在之後結果爲。
(抱歉劫持你的答案,但這對於評論來說也太大了)
是什麼讓你說它不工作?你能描述一下你的實際問題嗎? – 2014-10-07 22:25:01
引用提到PUSHD的主題標題,我同意CD不會持續,但pushd仍然存在,不是嗎?剛剛測試;批處理完成後,我確實從命令行彈出。 (甚至一對POPD每個工作) – MicrosoftShouldBeKickedInNuts 2017-12-21 18:53:32