2014-11-25 65 views
0

这里的问题是创建新的日志(如果不存在),或者追加到一个(如果它提供的话)(提供它不是太大) 问题由使用嵌套变量以%USERNAME%开始,然后是%LOGFILE%,然后是APPENDORNEW,尝试将APPENDORNEW组成一个命令。使用变量批量登录

REM Set way back at the beginning of the code several sub labels back 
setlocal DisableDelayedExpansion 
. 
. 
. 

Set LOGFILE=C:\Users\%USERNAME%\Documents\Logs\X.log 

REM Does the logfile exist already? 
REM Adjust redirection operators to create new log or appends to old log. 
REM Quotes make no difference 
If exist !%LOGFILE%! (set "_APPENDORNEW=^>^>" 
) else (set "_APPENDORNEW=^>") 

@echo on 
REM This displays nothing (as expected?) 
echo %_APPENDORNEW% 
set /p APPENDORNEW=!%_APPENDORNEW%%LOGFILE%! 

REM The display is just '\Users\%USERNAME%\Documents\Logs\X.log' 
REM with the username value- but what happened to the 'C:'? 

echo %APPENDORNEW% 

%APPENDORNEW%: (

REM This is the command that is supposed to go >LOGFILE or >>LOGFILE 
REM The cursor "hangs" here before enter resumes execution 
REM The colon was suggested somewhere else- but doesn't factor here 

echo Start time is: %date% %TIME% 
REM Do Commands 
REM This bracket is grouped within sub labels. 
) 

回答

3

>>要附加到文件也将创建文件,如果它不存在。有没有必要检查

@echo off 
    setlocal enableextensions disabledelayedexpansion 

    set "logFile=test.log" 
    for %%a in ("%logFile%") do if %%~za gtr 1000 (
     echo recycle log file 
     type nul > "%logFile%" 
    ) 

    set "operator=>>" 
    set "log=%operator% "%logFile%"" 

    for /l %%a in (1 1 10) do (
     %log% echo test %%a 
    ) 

    %log% (
     for /l %%a in (1 1 10) do echo test2 %%a 
    ) 

为什么不能在指定的文件大小检查operator?如果分配了>,则使用相同运算符的第二个for循环将覆盖第一个for循环的输出。为了避免重新定义运营商,它更容易使用>>

+0

我认为,尽管这个“功能失调”的代码,它没有发生。在括号中以上述方式使用似乎有区别。还有关于日志文件大小的警告。 – 2014-11-25 10:46:15

+0

@LaurieStearn,看来你的报价有问题。在答案中测试代码。 – 2014-11-25 10:53:00

+0

这工作正常。谢谢。如何将其包装到要记录的代码部分。只需在代码后插入:>>%logfile%(___codng___)? – 2014-11-25 11:01:20