1

The problem here is to create new log if one doesn't exist, or append to one if it does (providing it isn't too large) The problem is compounded by the use of nested variables beginning with %USERNAME% then %LOGFILE% then APPENDORNEW, trying to form APPENDORNEW into a command.

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.
)

1 Answer 1

4

>> to append to a file will also create the file if it does not exist. There is no need for the check

@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
    )

Why not assign the operator in the file size check? If a > is assigned, the second for loop, that is using the same operator, will overwrite the output from the first for loop. To avoid having to redefine the operator, it is easier to use >>

Sign up to request clarification or add additional context in comments.

4 Comments

I thought as much, yet with this "dysfunctional" code it wasn't happening. Used in above way with brackets there seemed to be a difference. Also the caveat on size of the logfile.
@LaurieStearn, It seems you have problems with your quotes. Test the code in the answer.
That works fine. Thanks. How does one wrap that in to a code section to be logged. Just insert after your code: >>%logfile% (codng) ?
@LaurieStearn, answer updated, see the second for loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.