Home > OS >  Windows 10 - Clearing Event Logs in CMD batch script with all output running on same line?
Windows 10 - Clearing Event Logs in CMD batch script with all output running on same line?

Time:10-22

I have a batch script which part of it is clearing the Event logs of Windows. I would like to see the output of the following wevtutil.exe command, but output just on a single line (overwriting each line) instead of many multiple lines.

I know about the VT100 escape codes ESC[1FESC[0J and ESC[1A which can overwrite a previous line (The ESC char is ALT 027 and can be seen in Notepad ), but I haven't been able to figure out how to do that with the wevtutil.exe el command. It still outputs each line one after the other. Here's what I tried (running in CMD with admin rights):

@echo off
SET OverwriteLine=ESC[1FESC[0J
echo Making sure the variable OverwriteLine actually works. This is line 1.
echo %OverwriteLine%If you see this line instead of line 1, OverwriteLine works.
echo Great, now let^'s see if it works for the "wevtutil.exe cl" command
pause
echo Clearing Event logs...
@echo on
for /F "tokens=*" %%E in ('wevtutil.exe el') DO echo %OverwriteLine% | wevtutil.exe cl "%%E"
pause

I know this can be done via Powershell's $host.ui.RawUI.CursorPosition, but I need a solution for CMD/BAT.

CodePudding user response:

As we deal with a single specific issue per question, and your main one appears to be with the implementation of the VT100 sequences, here is a commented example using a completely different for loop just for demonstration of the technique.

@Echo Off
SetLocal EnableExtensions
Rem Create a variable to use as the escape character
For /F %%G In ('Echo Prompt $E ^| %SystemRoot%\System32\cmd.exe') Do Set "\x1b=%%G"
Rem This is a static line included to demonstrate that it is unaffected
Echo(Output
Rem Turns off the cursor and removes a stray new line caused by Echo
Echo(%\x1b%[?25l%\x1b%[1A
Rem For loop example
For /L %%G In (1,1,8) Do (
    Rem Clears to the beginning of the line, prints the output, and moves up a line
    Echo(%\x1b%[1KLine %%G%\x1b%[1A
    Rem Creates a short delay between output lines to see the effect
    %SystemRoot%\System32\PATHPING.EXE 127.0.0.1 -n -q 1 -p 650 1>NUL
)
Rem Turns on the cursor again
Echo(%\x1b%[?25h
Pause

CodePudding user response:

OK, found the solution:

for /F "tokens=*" %%E in ('wevtutil.exe el') DO (wevtutil.exe cl "%%E" | echo <ESC>[1FClearing %%E<ESC>[0J)

< ESC> means the special ESC escape code. You can press ALT 027 in Notepad if you're editing your code in there, or generate this escape code using the FOR loop that Compo mentioned:

For /F %%G In ('Echo Prompt $E ^| %SystemRoot%\System32\cmd.exe') Do Set "\x1b=%%G"

For those interested, you can find complete info about escape codes here.

  • Related