我試圖從批處理文件中讀取文本文件並將其作爲批處理文件中的變量執行。有一個批處理文件從保存箱中讀取文本文件,並將其作爲變量在批處理文件中執行
這是我正在嘗試,但它不起作用,請幫助!
SetLocal EnableDelayedExpansion
set content=
for /F "delims=" %%i in (DROPBOX-LINK-HERE) do set content=!
content! %%i
%content%
EndLocal
我試圖從批處理文件中讀取文本文件並將其作爲批處理文件中的變量執行。有一個批處理文件從保存箱中讀取文本文件,並將其作爲變量在批處理文件中執行
這是我正在嘗試,但它不起作用,請幫助!
SetLocal EnableDelayedExpansion
set content=
for /F "delims=" %%i in (DROPBOX-LINK-HERE) do set content=!
content! %%i
%content%
EndLocal
我不確定你的意思是DROPBOX-LINK-HERE
,但我使用普通的文本文件作爲內容。
您必須將每行與&
分隔開,否則將內容括在括號內,並將每行與<linefeed>
分開。換行解決方案更復雜,但對內容的限制更少。
任何!
如果啓用延遲擴展,則在FOR變量擴展期間內容中的字符將被破壞。但需要延遲擴展才能保留未引用的特殊字符。所以延遲擴展需要創造性地開關。
這裏是代碼,我認爲做你想做的。
@echo off
setlocal disableDelayedExpansion
::Define a carriage return variable
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
::Create a newline variable
set LF=^
::The above 2 blank lines are critical - do not remove
::Both CR and LF should be expanded using delayed expansion only.
::Load the content into a variable.
::We want to separate lines with linefeed, but FOR /F won't preserve linefeeds.
::So use carriage return as a place holder for now.
set "content=("
setlocal enableDelayedExpansion
for /f %%C in ("!CR! ") do (
endlocal
for /f "delims=" %%A in (test.txt) do (
setlocal enableDelayedExpansion
for /f "delims=" %%B in ("!content!") do (
endlocal
set "content=%%B%%C%%A"
)
)
)
::Now replace carriage returns with newline and append terminating)
setlocal enableDelayedExpansion
for /f %%C in ("!CR! ") do for %%N in ("!LF!") do set "content=!content:%%C=%%~N!%%~N)"
::Execute the content
endlocal&%content%
該代碼有效,但是可以從變量執行的代碼類型存在限制。
除非您使用CALL,否則變量不能通過正常擴展進行擴展。例如,像echo %var%
這樣的行將不起作用,但call echo %var%
將起作用。另一種選擇是使用延遲擴展。根據需要可以將SETLOCAL EnableDelayedExpansion
和ENDLOCAL
包含在內容中。
您不能在CALL
或GOTO
a :LABEL
之內的內容。
這就是我現在所記得的,但可能有(可能是)其他限制。
我有一個問題,但:
如果內容已經在一個文本文件,那麼爲什麼不乾脆放棄了文本文件.bat擴展名並執行它?
+1(與往常一樣)有時真的存在簡單的說明:-)'爲什麼不簡單地給文本文件一個.BAT擴展名並執行它呢?但你的解決方案更先進...... – jeb
我並不完全確定自己很清楚你想要做什麼。您能否請您發佈一個文本文件樣本,然後指定您希望執行此批處理腳本的結果? –