@setlocal DisableDelayedExpansion
@echo off
set "_args=%*"
set "_elv="
if not defined _args goto :NoProgArgs
if "%~1"=="" set "_args="&goto :NoProgArgs
set _args=%_args:"=%
for %%A in (%_args%) do (
if /i "%%A"=="-wow" (set _rel1=1) else if /i "%%A"=="-arm" (set _rel2=1)
)
:NoProgArgs
set "_cmdf=%~f0"
if exist "%SystemRoot%\Sysnative\cmd.exe" if not defined _rel1 (
setlocal EnableDelayedExpansion
start %SystemRoot%\Sysnative\cmd.exe /c ""!_cmdf!" -wow %*"
exit /b
)
if exist "%SystemRoot%\SysArm32\cmd.exe" if /i %PROCESSOR_ARCHITECTURE%==AMD64 if not defined _rel2 (
setlocal EnableDelayedExpansion
start %SystemRoot%\SysArm32\cmd.exe /c ""!_cmdf!" -arm %*"
exit /b
)
set "SysPath=%SystemRoot%\System32"
set "Path=%SystemRoot%\System32;%SystemRoot%\System32\Wbem;%SystemRoot%\System32\WindowsPowerShell\v1.0\"
if exist "%SystemRoot%\Sysnative\reg.exe" (
set "SysPath=%SystemRoot%\Sysnative"
set "Path=%SystemRoot%\Sysnative;%SystemRoot%\Sysnative\Wbem;%SystemRoot%\Sysnative\WindowsPowerShell\v1.0\;%Path%"
)
set "_err===== ERROR ===="
reg query HKU\S-1-5-19 1>nul 2>nul || goto :E_Admin

set "_wrn===== WARNING ===="
set "_WUA=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"

if exist "%SystemRoot%\WinSxS\pending.xml" (
echo %_wrn%
echo Pending update operation detected.
echo Restart the system first, then run the script.
goto :TheEnd
)

:Begin
@cls
echo.
choice /C YN /N /M "Defragment DataStore.edb? [y/n]: "
if errorlevel 2 exit

call :sharedB
sc query wuauserv 2>nul | find /i "STOPPED" 1>nul || goto :E_Svc
pushd %SystemRoot%\SoftwareDistribution\DataStore
esentutl /d DataStore.edb
call :sharedE

echo.
echo Done.
goto :TheEnd

:sharedB
set "_abak=0x1"
for /f "skip=2 tokens=2*" %%a in ('reg query "%_WUA%" /v AUOptions 2^>nul') do set "_abak=%%b"
reg query "%_WUA%" /v AUOptions_bak 1>nul 2>nul && for /f "skip=2 tokens=2*" %%a in ('reg query "%_WUA%" /v AUOptions_bak 2^>nul') do set "_abak=%%b"
1>nul 2>nul reg add "%_WUA%" /f /v AUOptions /t REG_DWORD /d 0x1
1>nul 2>nul reg add "%_WUA%" /f /v AUOptions_bak /t REG_DWORD /d %_abak%
echo.
echo - Stop related services
call :StopService sppsvc 1>nul 2>nul
call :StopService BITS 1>nul 2>nul
call :StopService TrustedInstaller 1>nul 2>nul
call :StopService wuauserv 1>nul 2>nul
exit /b

:sharedE
1>nul 2>nul reg add "%_WUA%" /f /v AUOptions /t REG_DWORD /d %_abak%
1>nul 2>nul reg delete "%_WUA%" /f /v AUOptions_bak
exit /b

:StopService
sc query %1 | find /i "STOPPED" || net stop %1 /y
sc query %1 | find /i "STOPPED" || sc stop %1
exit /b

:E_Svc
call :sharedE
echo %_err%
echo Failed stopping Windows Update service.
echo Restart the system first, then run the script.
goto :TheEnd

:E_Admin
echo %_err%
echo This script requires administrator privileges.
goto :TheEnd

:TheEnd
echo.
echo Press any key to exit.
pause >nul
goto :eof
