2012-08-14 173 views
3

我在寫一個Windows批處理文件,它將清除超過90天的日誌。如何連接命令的輸出以便它們出現在一行中?我也想在稍後將此輸出附加到文件中。我的批處理文件,到目前爲止是:如何連接Windows批處理文件的命令輸出

@echo off  
time /t && echo "--" && date /t && echo " -I- Purging " && FORFILES /P "D:\Logs" /M *.log /D -90 /C "cmd /c echo @file @fdate" 
rem FORFILES that will purge the files 

這種輸出:

12:08 
-- 
14/08/2012 
-I- Purging 

"<filename>" 02/08/2012 
"<filename>" 30/07/2012 

我如何可以連接這些輸出?謝謝。

回答

1

如果你想連接的輸出線,可以設置CMD_STR是你需要的命令,並使用for /f循環,就像這樣:通過輸出線

@echo off 
setlocal enabledelayedexpansion 
set "CMD_STR=time /t && echo "--" && date /t && echo " -I- Purging " && FORFILES /P "D:\Logs" /M *.log /D -90 /C "cmd /c echo @file @fdate"" 
set CONCAT_STR= 
for /f %%i in ('%CMD_STR%') do set "CONCAT_STR=!CONCAT_STR! %%i" 
echo !CONCAT_STR! 

循環迭代並將它們逐一追加到CONCAT_STR

+1

謝謝,但我需要用%% CMD_STR %%替換%CMD_STR%並在清除之前添加另一個'echo'以使其工作。 – TomaszRykala 2012-08-14 12:38:30

+0

這樣做。謝謝。 – TomaszRykala 2012-08-14 12:41:03

+0

@TomaszRykala很高興幫助。爲什麼'%%'? – 2012-08-14 12:44:10

4

將所有內容放在除FOR之外的其他行上很容易。你只需要使用 動態%TIME%和%DATE%變量,而不是時間和日期命令

@echo off  
echo %time% "--" %date% -I- Purging 
FORFILES /P "D:\Logs" /M *.log /D -90 /C "cmd /c echo @file @fdate" 
rem FORFILES that will purge the files 

如果您還想要的文件名出現在同一行,那麼你可以使用一個臨時像EitanT建議的那樣變化。但是這限制了文件的數量以適應最大8191變量大小。要處理無限數量的文件,您可以使用SET/P代替。似乎FOR/F聲明似乎不是必要的,但有一個引用問題,如果沒有它,我就無法解決。

@echo off 
<nul (
    set/p="%time% -- %date% -I- Purging " 
    for /f "delims=" %%A in (
    'FORFILES /P "D:\Logs" /M *.log /D -90 /C "cmd /c echo @file @fdate"' 
) do set/p="%%A " 
) 
rem FORFILES that will purge the files 

沒有理由不在清除文件的同時列出它們。由於FORFILES速度很慢,因此在相同的命令中進行清除和列表會更有效率。

@echo off 
<nul (
    set/p="%time% -- %date% -I- Purging " 
    for /f "delims=" %%A in (
    'FORFILES /P "D:\Logs" /M *.log /D -90 /C "cmd /c del @path&echo @file @fdate"' 
) do set/p="%%A " 
) 


更新2015年1月6日

我想出了一個解決方案,而無需使用FOR/F。我使用0x22將引號中的SET/P提示符括起來,並使用FINDSTR消除FORFILES在請求輸出之前寫入的空行。

@echo off 
<nul (
    set/p="%time% -- %date% -I- Purging " 
    forfiles /p "d:\logs" /m *.log /d -90 /c "cmd /c del @path&set/[email protected] @fdate 0x5e0x22"'|findstr . 
) 
+0

我最喜歡的解決方案可以將時間戳記分成臨時批次 – Wolf 2015-12-08 12:16:11

+1

不錯,但是您錯過了'set/p = 0x5E0x22..'處的插入符號'0x5E',以避免出現' &'在文件名中 – jeb 2016-01-06 15:06:08

+0

@jeb -ooh,很好。謝謝。我已經更新了我的答案。 – dbenham 2016-01-06 15:29:10