2012-08-14 176 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