我不完全熟悉命令行脚本。我正在尝试创建一个批处理文件来读取txt文件,应用一种格式将文件从报表转换为表格,然后将该文件导出为电子表格。
我可以让脚本适用于单个文件但是如果我尝试通过循环运行多个文件就没有任何反应。它启动程序遍历每个脚本行,但再也没有做任何事情。它没有设置路径。没有崩溃。在哪里我将脚本从循环中取出并将其应用于单个文件,它可以正常工作。有什么建议吗?
SET monarch_bin="C:\Program Files (x86)\Datawatch\Monarch\Program\Monarch.exe"
for /f "delims=" %%i in ('dir /b "C:\Users\Me\Desktop\Sample Monarach Input\*.txt"') do (
echo File directory : %%i
SET infilename=/Rpt: "C:\Users\Me\Desktop\Sample Monarach Input\%%i.txt"
echo ####### In file name:%infilename%
SET model_file=/mod:"C:\Users\Me\Desktop\Sample Monarach Input\InvoiceSummary.xmod"
echo ####### Model: %model_file%
SET outfilename=/exp:"C:\Users\Me\Desktop\Sample Monarach Input\OUTPUT.xlsx"
echo ####### Out file name:%outfilename%
SET mode=/expfileopt:append /T
echo ####### File: %%i
%monarch_bin%%infilename%%model_file%%outfilename%%mode%
pause
)
答案 0 :(得分:1)
延迟扩展问题(解释here)
setlocal enabledelayedexpansion
SET monarch_bin="C:\Program Files (x86)\Datawatch\Monarch\Program\Monarch.exe"
for /f "delims=" %%i in ('dir /b "C:\Users\Me\Desktop\Sample Monarach Input\*.txt"') do (
echo File directory : %%i
SET infilename=/Rpt:"C:\Users\Me\Desktop\Sample Monarach Input\%%i.txt"
echo ####### In file name: !infilename!
SET model_file=/mod:"C:\Users\Me\Desktop\Sample Monarach Input\InvoiceSummary.xmod"
echo ####### Model: !model_file!
SET outfilename=/exp:"C:\Users\Me\Desktop\Sample Monarach Input\OUTPUT.xlsx"
echo ####### Out file name: !outfilename!
SET mode=/expfileopt:append /T
echo ####### File: %%i
%monarch_bin% !infilename! !model_file! !outfilename! !mode!
)
如果在代码块中更改了变量值,则需要延迟扩展以检索同一代码块中的更改值。
但是,这可以写成
set "monarch_bin=C:\Program Files (x86)\Datawatch\Monarch\Program\Monarch.exe"
set "inputFolder=C:\Users\Me\Desktop\Sample Monarach Input"
for %%i in ("%inputFolder%\*.txt") do (
"%monarch_bin%" ^
/Rpt:"%%~fi" ^
/mod:"%%~dpiInvoiceSummary.xmod" ^
/exp:"%%~dpioutput.xlsx" ^
/expfileopt:append /T
)
for
循环将遍历.txt
文件列表,而%%i
将保留对该文件的引用,%%~fi
是完整路径文件和%%~dpi
是存储文件的驱动器和路径。