2014-11-25 59 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