我回到這里是為了另一個問題,這次是關于宏。
我想使用 !..! 來呼叫多行宏 (如果可能的話)為了使用動態宏名稱,如下面的單行宏呼叫:
setlocal disabledelayedexpansion
:: Simple single-line macros for testing purpose.
set "_testA=echo A" & set "_testB=echo B"
setlocal enabledelayedexpansion
:: Choose macro _testA or _testB.
set /p char="Type A or B:"
:: Execute the chosen macro.
!_test%char%!
endlocal
endlocal
例如,
setlocal disabledelayedexpansion
:: Line feed character.
(set CHR10=^
%=Do not remove this line, or you will be turned into a frog=%
)
:: End of line in a macro code.
set ^"\nmac=^^^%CHR10%%CHR10%^%CHR10%%CHR10%^^"
:: Simple multi-line macro for testing purpose, it could be replace with one receiving parameters obviously.
set _test=(echo A%\nmac%
echo B%\nmac%
echo C)
setlocal enabledelayedexpansion
:: Works as expected, displays A then B then C.
%_test%
:: Doesn't work... as expected also, displays `(echo Is Not Recognized as an Internal or External Command, Operable Program or Batch File.`
!_test!
endlocal
endlocal
問題似乎來自使用 with !..! 時 CHR10 的定義。(顯然,使用 %_test% 有效)。
有什么辦法解決這個問題嗎?一個解決方案可以幫助我重構一些代碼。
提前感謝您的回答。
uj5u.com熱心網友回復:
解決方案很簡單,您總是需要百分比擴展來執行批處理宏。顯然,您不能為百分比擴展使變數名稱動態化,但您可以使內容動態化。
@echo off
(set ^"$\n=^^^
%= Do not remove this line=%
)
set macro1=(echo #1 Line1 %$\n%
echo #1 Line2)
set macro2=(echo #2 Line1 %$\n%
echo #2 Line2)
setlocal EnableDelayedExpansion
%macro1%
%macro2%
set /p "macroNum=Select 1 or 2: "
set "macroName=macro%macroNum%"
REM *** Copy the content of the 'dynamic macro' to indirectMacro
set "indirectMacro=!%macroName%!"
%indirectMacro%
順便提一句。您的定義和使用\nmac是多余的,因為linefeed在批處理宏中,單個(帶有單個插入符號)就足夠了,當它們被括在括號中時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451394.html
上一篇:在新終端中運行命令,然后稍后殺死
