@echo off

setlocal
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS

set ResultLine1=
set ResultLine2=
set OLDDIRSLASH=%~dp0

set SYSFILE=%SystemRoot%\system32\wmi.dll
del %SYSFILE%.bak >nul 2>&1
copy %SYSFILE% %SYSFILE%.bak >nul 2>&1
if NOT EXIST %SYSFILE%.bak (
    set ResultLine1=The script must run in elevated command prompt
    goto end
   )
del %SYSFILE%.bak >nul 2>&1

:: Get timestamp
for /f "tokens=2-4 delims=/ " %%i in ('echo %date%') do set _DATETIME=%%k%%i%%j
for /f "tokens=1-3 delims=:. " %%i in ('echo %time%') do set _DATETIME=%_DATETIME%-%%i%%j%%k

:: Get build info
for /f "skip=2 tokens=3,4,5,6,7 delims=. " %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v BuildLabEx') do set _BUILD=%%d.%%a.%%e.%%c

set folder=%OLDDIRSLASH%%_DATETIME%_%USERNAME%_%COMPUTERNAME%

md "%folder%"

if NOT EXIST "%folder%" (
    set ResultLine1=[%folder%]
    set ResultLine2=Could not create the output folder.
    goto end
)

echo on
"xperf.exe" -stop 1stLogonLogger
@echo off
if NOT ERRORLEVEL 0 (
    set ResultLine1=[xperf.exe]
    set ResultLine2=Failed to flush the trace. Error = %ERRORLEVEL%
    goto end
)

echo ETW Tracing stopped OK

:: Do not trace anymore
reg add "HKLM\System\ControlSet001\Control\WMI\Autologger\1stLogonLogger" /v Start /t REG_DWORD /d 0 /f

for %%i in (%windir%\System32\LogFiles\WMI\1stLogonLogger.etl.???) do (
  echo on
  "xperf.exe" -merge "%%i" "%folder%\%%~nxi.merged.etl"
  @echo off
  del /q "%%i"
)

echo Merged traces OK

robocopy %windir%\System32\winevt           "%folder%\logs\winevt"                     /MIR
robocopy %windir%\Panther                   "%folder%\logs\Panther"                    /MIR
robocopy %windir%\Logs                      "%folder%\logs\Logs"                       /MIR
robocopy %windir%\System32\Sysprep\Panther  "%folder%\logs\Sysprep"                    /MIR
robocopy %windir%\Microsoft.NET             "%folder%\logs\ngen"     ngen.log          /s
robocopy %windir%                           "%folder%\logs\wu"       windowsupdate.log
wmic qfe >                                  "%folder%\logs\qfes.txt"

:end

if "%ResultLine1%" neq "" echo %ResultLine1%
if "%ResultLine2%" neq "" echo %ResultLine2%

EndLocal
