@setlocal DisableDelayedExpansion
@echo off



::============================================================================
::
::   此脚本是“Microsoft 激活脚本”（MAS）项目中的一部分
::
::   主    页：windowsaddict.ml
::      Email：windowsaddict@protonmail.com
::
::============================================================================




::========================================================================================================================================

:: 如果脚本是由 x64 位 Windows 上的 x86 进程启动的，则将使用 x64 进程重新启动脚本
:: 或者如果它是由 ARM64 Windows 上的 x86/ARM32 进程启动的，则将使用 ARM64 进程

if exist %SystemRoot%\Sysnative\cmd.exe (
set "_cmdf=%~f0"
setlocal EnableDelayedExpansion
start %SystemRoot%\Sysnative\cmd.exe /c ""!_cmdf!" %*"
exit /b
)

:: 如果脚本是由 ARM64 Windows 上的 x64 进程启动的，则将使用 ARM32 进程重新启动脚本

if exist %SystemRoot%\SysArm32\cmd.exe if %PROCESSOR_ARCHITECTURE%==AMD64 (
set "_cmdf=%~f0"
setlocal EnableDelayedExpansion
start %SystemRoot%\SysArm32\cmd.exe /c ""!_cmdf!" %*"
exit /b
)

:: 设置路径变量，如果在系统中配置错误时会有所帮助

set "SysPath=%SystemRoot%\System32"
if exist "%SystemRoot%\Sysnative\reg.exe" (set "SysPath=%SystemRoot%\Sysnative")
set "Path=%SysPath%;%SystemRoot%;%SysPath%\Wbem;%SysPath%\WindowsPowerShell\v1.0\"

::========================================================================================================================================

cls
color 07
title  激活疑难解答

set _elev=
if /i "%~1"=="-el" set _elev=1

set winbuild=1
set "nul=>nul 2>&1"
set "_psc=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
for /f "tokens=6 delims=[]. " %%G in ('ver') do set winbuild=%%G

set _NCS=1
if %winbuild% LSS 10586 set _NCS=0
if %winbuild% GEQ 10586 reg query "HKCU\Console" /v ForceV2 2>nul | find /i "0x0" 1>nul && (set _NCS=0)

call :_colorprep

set slp=SoftwareLicensingProduct
set sls=SoftwareLicensingService
set ospp=OfficeSoftwareProtectionProduct
set wApp=55c92734-d682-4d71-983e-d6ec3f16059f
set cbs_log=%SystemRoot%\logs\cbs\cbs.log
set "nceline=echo: &echo ==== 出现错误 ==== &echo:"
set "eline=echo: &call :_color %Red% "==== 出现错误 ====" &echo:"
set "line=_________________________________________________________________________________________________"

::========================================================================================================================================

if %winbuild% LSS 7600 (
%nceline%
echo 检测到不受支持的操作系统版本。
echo 项目仅支持 Windows 7/8/8.1/10/11 及它们对应的 Server 版本。
goto at_done
)

if not exist %_psc% (
%nceline%
echo 在系统中未安装 Powershell。
echo 正在中止……
goto at_done
)

::========================================================================================================================================

::  修复路径名称中的特殊字符限制

set "_batf=%~f0"
set "_batp=%_batf:'=''%"

set "_PSarg="""%~f0""" -el %_args%"

set "_ttemp=%temp%"

setlocal EnableDelayedExpansion

::========================================================================================================================================

echo "!_batf!" | find /i "!_ttemp!" 1>nul && (
%nceline%
echo 脚本是从 temp 文件夹启动的，
echo 最有可能的原因是，你是直接从压缩文件运行脚本。
echo:
echo 请解压压缩文件并从解压文件夹中启动脚本。
goto at_done
)

::========================================================================================================================================

:: 将脚本提升为管理员权限及传递参数并防止循环

%nul% reg query HKU\S-1-5-19 || (
if not defined _elev %nul% %_psc% "start cmd.exe -arg '/c \"!_PSarg:'=''!\"' -verb runas" && exit /b
%nceline%
echo 此脚本需要以管理员权限运行。
echo 若要继续执行，请在脚本上右键单击并选择“以管理员权限运行”
goto at_done
)

::========================================================================================================================================

setlocal DisableDelayedExpansion

::  检查桌面位置

set desktop=
for /f "skip=2 tokens=2*" %%a in ('reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop') do call set "desktop=%%b"
if not defined desktop for /f "delims=" %%a in ('%_psc% "& {write-host $([Environment]::GetFolderPath('Desktop'))}"') do call set "desktop=%%a"

if not defined desktop (
%eline%
echo 桌面位置未被检测到，正在中止……
goto at_done
)

setlocal EnableDelayedExpansion

::========================================================================================================================================

:at_menu

cls
color 07
title  激活疑难解答
mode con cols=77 lines=30

echo:
echo:
echo:
echo:       _______________________________________________________________
echo:                                                   
echo:             [1] 疑难解答自述文件    - HWID        
echo:             [2] 疑难解答自述文件    - KMS38
echo:             [3] 疑难解答自述文件    - 在线 KMS
echo:             ___________________________________________________      
echo:                                                                      
echo:             [4] Dism RestoreHealth                                   
echo:             [5] SFC Scannow                                          
echo:                                                                      
echo:             [6] Windows Rearm - 特定 SKU ID
echo:             [7] Office  Rearm - 特定 KMS SKU ID
echo:
echo:             [8] 清理 ClipSVC 许可证
echo:             [9] 重建许可令牌
echo:                                                                      
echo:             [F] Office 许可证不是正版 - 通知
echo:
echo:             [0] 退出                                               
echo:       _______________________________________________________________
echo:          
call :_color2 %_White% "            " %_Green% "请在键盘中输入菜单选项 ："
choice /C:123456789F0 /N
set _erl=%errorlevel%

if %_erl%==11 exit /b
if %_erl%==10 start https://windowsaddict.ml/office-license-is-not-genuine &goto at_menu
if %_erl%==9 goto:retokens
if %_erl%==8 goto:cleanclipsvc
if %_erl%==7 goto:officerearm
if %_erl%==6 goto:rearmwin
if %_erl%==5 goto:sfcscan
if %_erl%==4 goto:dism_rest
if %_erl%==3 start https://windowsaddict.ml/readme-troubleshoot-onlinekms.html &goto at_menu
if %_erl%==2 start https://windowsaddict.ml/readme-troubleshoot-kms38.html &goto at_menu
if %_erl%==1 start https://windowsaddict.ml/readme-troubleshoot-hwid.html &goto at_menu
goto :at_menu

::========================================================================================================================================

:dism_rest

cls
mode 98, 30
title  Dism /Online /Cleanup-Image /RestoreHealth

if %winbuild% LSS 9200 (
%eline%
echo 检测到不受支持的操作系统版本。
echo 仅限 Windows 8/8.1/10/11 及其对应的 Server 支持此命令。
goto :at_back
)

set _int=
for %%a in (dns.msftncsi.com,www.microsoft.com,one.one.one.one,resolver1.opendns.com) do (
if not defined _int (for /f "delims=[] tokens=2" %%# in ('ping -n 1 %%a') do if not [%%#]==[] set _int=1))

echo:
if defined _int (
echo      正在检查 Internet 连接           [已连接]
) else (
call :_color2 %_White% "     " %Red% "正在检查 Internet 连接           [未连接]"
)

echo %line%
echo:
echo      Dism 使用 Windows 更新来提供修复损坏所需的文件。
echo      这将需要 5-15 分钟或更长时间……
echo %line%
echo:
echo      注：
echo:
call :_color2 %_White% "     - " %Gray% "请确保 Internet 已连接。"
call :_color2 %_White% "     - " %Gray% "请确保 Windows 更新正常工作。"
echo:
echo %line%
echo:
choice /C:29 /N /M ">    [9] 继续 [2] 返回 ："
if %errorlevel%==1 goto at_menu

cls
mode 110, 30
echo:

call :_stopservice TrustedInstaller
del /s /f /q "%SystemRoot%\logs\cbs\*.*"

set _time=
for /f %%a in ('%_psc% "Get-Date -format HH_mm_ss"') do set _time=%%a
echo:
echo 正在应用命令，
echo dism /online /cleanup-image /restorehealth /Logpath:"%SystemRoot%\Temp\RHealth_DISM_%_time%.txt" /loglevel:4
echo:
dism /online /cleanup-image /restorehealth /Logpath:"%SystemRoot%\Temp\RHealth_DISM_%_time%.txt" /loglevel:4

if not exist "!desktop!\AT_Logs\" md "!desktop!\AT_Logs\" %nul%
copy /y /b "%SystemRoot%\Temp\RHealth_DISM_%_time%.txt" "!desktop!\AT_Logs\RHealth_DISM_%_time%.txt" %nul%
copy /y /b "%cbs_log%" "!desktop!\AT_Logs\RHealth_CBS_%_time%.txt" %nul%
del /f /q "%SystemRoot%\Temp\RHealth_DISM_%_time%.txt" %nul%

echo:
call :_color %Gray% "CBS 和 DISM 日志已被复制到桌面上的 AT_Logs 文件夹中。"
goto :at_back

::========================================================================================================================================

:sfcscan

cls
mode 98, 30
title  sfc /scannow

echo:
echo %line%
echo:    
echo      系统文件检查器（System File Checker）将修复丢失或损坏的系统文件。
echo      这将需要 10-15 分钟或更长时间……
echo:
echo      如果 SFC 无法修复某些问题，则再次运行该命令以查看下一次是否能够修复。 有时可能需
echo      要运行 sfc /scannow 命令 3 次，每次之后重新启动 PC 才能完全修复它能够修复的所有问
echo      题。
echo:   
echo %line%
echo:
choice /C:29 /N /M ">    [9] 继续 [2] 返回 ："
if %errorlevel%==1 goto at_menu

cls
echo:

call :_stopservice TrustedInstaller
del /s /f /q "%SystemRoot%\logs\cbs\*.*"

set _time=
for /f %%a in ('%_psc% "Get-Date -format HH_mm_ss"') do set _time=%%a
echo:
echo 正在应用命令，
echo sfc /scannow
echo:
sfc /scannow

if not exist "!desktop!\AT_Logs\" md "!desktop!\AT_Logs\" %nul%

copy /y /b "%cbs_log%" "!desktop!\AT_Logs\SFC_CBS_%_time%.txt" %nul%
findstr /i /c:"[SR]" %cbs_log% | findstr /i /v /c:verify >"!desktop!\AT_Logs\SFC_Main_%_time%.txt"

echo:
call :_color %Gray% "CBS 和主要提取的日志被复制到桌面上的 AT_Logs 文件夹中。"
goto :at_back

::========================================================================================================================================

:rearmwin

cls
mode 98, 30
title  Windows Rearm - 特定 SKU ID

if %winbuild% LSS 9600 (
%eline%
echo 检测到不受支持的操作系统版本。
echo 仅限 Windows 8/8.1/10/11 及其对应的 Server 支持此命令。
goto :at_back
)

echo:
echo %line%
echo:    
echo      注：
echo:
echo       - Rearm 有助于解决激活问题。
echo:
echo       - Windows KMS 激活将被重置。
echo:
echo %line%
echo:
choice /C:29 /N /M ">    [9] 继续 [2] 返回 ："
if %errorlevel%==1 goto at_menu

cls
mode 105, 30
echo:
echo:
set app=
net start sppsvc /y %nul%
if %winbuild% LSS 22483 for /f "tokens=2 delims==" %%a in ('"wmic path %slp% where (ApplicationID='%wApp%' and PartialProductKey is not NULL) get ID /VALUE" 2^>nul') do call set "app=%%a"
if %winbuild% GEQ 22483 for /f "tokens=2 delims==" %%a in ('%_psc% "(([WMISEARCHER]'SELECT ID FROM %slp% WHERE ApplicationID=''%wApp%'' AND PartialProductKey IS NOT NULL').Get()).ID | %% {echo ('ID='+$_)}" 2^>nul') do call set "app=%%a"

if defined app (
if %winbuild% LSS 22483 for /f "tokens=2 delims==" %%x in ('"wmic path %slp% where ID='%app%' get Name /VALUE" 2^>nul') do echo Rearming: %%x
if %winbuild% GEQ 22483 for /f "tokens=2 delims==" %%x in ('%_psc% "(([WMISEARCHER]'SELECT Name FROM %slp% WHERE ID=''%app%''').Get()).Name | %% {echo ('Name='+$_)}" 2^>nul') do echo Rearming: %%x
echo:
echo 正在应用命令，
if %winbuild% LSS 22483 (
echo wmic path %slp% where ID='%app%' call ReArmsku
wmic path %slp% where ID='%app%' call ReArmsku %nul%
)
if %winbuild% GEQ 22483 (
echo Powershell "$null=([WMI]'%slp%=''%app%''').ReArmsku()"
%_psc% "$null=([WMI]'%slp%=''%app%''').ReArmsku()" %nul%
)
if !errorlevel!==0 (
call :_color %Green% "[成功]"
) else (
call :_color %Red% "[失败]"
)
) else (
call :_color %Red% "出现错误 - 未找到激活 ID"
)

goto :at_back

::========================================================================================================================================

:officerearm

cls
mode 98, 30
title  Office Rearm - 特定 KMS SKU ID

if %winbuild% LSS 9600 (
%eline%
echo 检测到不受支持的操作系统版本。
echo 仅限 Windows 8/8.1/10/11 及其对应的 Server 支持此命令。
goto :at_back
)

echo:
echo %line%
echo:   
echo      注：
echo:
echo       - Rearm 有助于解决激活问题。
echo:
echo       - Office KMS 激活将被重置。
echo:
call :_color2 %_White% "      - " %Gray% "Office rearm 只能应用一定次数。"
echo:
echo %line%
echo:
choice /C:29 /N /M ">    [9] 继续 [2] 返回 ："
if %errorlevel%==1 goto at_menu

cls
mode 105, 30
echo:

net start sppsvc /y %nul%
call :getapplist %slp%

if defined applist (
for %%# in (%applist%) do (
echo:
if %winbuild% LSS 22483 for /f "tokens=2 delims==" %%x in ('"wmic path %slp% where ID='%%#' get Name /VALUE" 2^>nul') do echo Rearming: %%x
if %winbuild% GEQ 22483 for /f "tokens=2 delims==" %%x in ('%_psc% "(([WMISEARCHER]'SELECT Name FROM %slp% WHERE ID=''%%#''').Get()).Name | %% {echo ('Name='+$_)}" 2^>nul') do echo Rearming: %%x
echo:
echo 正在应用命令，
if %winbuild% LSS 22483 (
echo wmic path %slp% where ID='%%#' call ReArmsku
wmic path %slp% where ID='%%#' call ReArmsku %nul%
)
if %winbuild% GEQ 22483 (
echo Powershell "$null=([WMI]'%slp%=''%%#''').ReArmsku()"
%_psc% "$null=([WMI]'%slp%=''%%#''').ReArmsku()" %nul%
)
if !errorlevel!==0 (
call :_color %Green% "[成功]"
) else (
call :_color %Red% "[失败]"
)
)
) else (
echo:
echo 正在检查：无法找到 Office 2013-2021 的批量版本。
)

call :getapplist %ospp%

if defined applist (
if %winbuild% LSS 9200 (set _off=Office) else (set _off=Office 2010)
echo:
echo 正在跳过基于 OSPP 的‘!_off!’Rearm
)

goto :at_back

:getapplist

set applist=
if %winbuild% LSS 22483 set "chkapp=for /f "tokens=2 delims==" %%a in ('"wmic path %1 where (Name like '%%office%%' and Description like '%%KMSCLIENT%%' and PartialProductKey is not NULL) get ID /VALUE" 2^>nul')"
if %winbuild% GEQ 22483 set "chkapp=for /f "tokens=2 delims==" %%a in ('%_psc% "(([WMISEARCHER]'SELECT ID FROM %1 WHERE Name like ''%%office%%'' and Description like ''%%KMSCLIENT%%'' and PartialProductKey is not NULL').Get()).ID ^| %% {echo ('ID='+$_)}" 2^>nul')"
%chkapp% do (if defined applist (call set "applist=!applist! %%a") else (call set "applist=%%a"))
exit /b

::========================================================================================================================================

:retokens

cls
mode 98, 30
title  重建许可令牌和重新安装系统许可文件

echo:
echo %line%
echo:   
echo      注：
echo:
echo       - 重建许可令牌和重新安装系统许可文件
echo         它有助于对激活问题进行故障排除。
echo:
call :_color2 %_White% "      - " %Gray% "Windows 和 Office 激活可能会被重置，你可能需要再次激活它们。"
echo:
call :_color2 %_White% "      - " %Magenta% "此选项将卸载 Office 许可证和密钥。"
call :_color2 %_White% "        " %Magenta% "已安装的 Office 需要在打开 office 应用后自行修复，"
call :_color2 %_White% "        " %Magenta% "你还可能需要从 Windows 设置中的应用和功能修复 Office。"
echo:
call :_color2 %_White% "      - " %Gray% "脚本被设计为跳过重建令牌，产品可能会无法恢复其许可"
call :_color2 %_White% "        " %Gray% "证。"
echo:
call :_color2 %_White% "      - " %Red% "仅在必要时才会应用。"
echo:
echo %line%
echo:
choice /C:24 /N /M ">    [4] 继续 [2] 返回 ："
if %errorlevel%==1 goto at_menu

cls
mode 98, 30

set nosup=
set 68=HKLM\SOFTWARE\Microsoft\Office
set 86=HKLM\SOFTWARE\Wow6432Node\Microsoft\Office

%nul% reg query %68%\16.0\Common\InstallRoot /v Path                && set nosup=1 REM Office 2016 MSI x86-x64
%nul% reg query %86%\16.0\Common\InstallRoot /v Path                && set nosup=1 REM Office 2016 MSI x86
%nul% reg query %68%\15.0\Common\InstallRoot /v Path                && set nosup=1 REM Office 2013 MSI x86-x64
%nul% reg query %86%\15.0\Common\InstallRoot /v Path                && set nosup=1 REM Office 2013 MSI x86
%nul% reg query %68%\14.0\Common\InstallRoot /v Path                && set nosup=1 REM Office 2010 MSI x86-x64
%nul% reg query %86%\14.0\Common\InstallRoot /v Path                && set nosup=1 REM Office 2010 MSI x86
%nul% reg query %68%\14.0\CVH /f Click2run /k                       && set nosup=1 REM Office 2010 C2R x86-x64
%nul% reg query %86%\14.0\CVH /f Click2run /k                       && set nosup=1 REM Office 2010 C2R x86

if %winbuild% GEQ 10240 reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\msoxmled.exe" %nul% && (
dir /b "%ProgramFiles%\WindowsApps\Microsoft.Office.Desktop*" %nul% && set nosup=1 REM Office UWP x86-x64
dir /b "%ProgramW6432%\WindowsApps\Microsoft.Office.Desktop*" %nul% && set nosup=1 REM Office UWP x86
)

sc qc osppsvc %nul% && (
if %winbuild% LSS 9200 (set _off=Office) else (set _off=Office 2010)
echo:
echo 正在跳过为检测到的“!_off!”重建 OSPP 令牌
)

echo:
if defined nosup (
echo 已检测到的 Office 可能无法自行修复，因此跳过 SPP 令牌重建……
goto :at_back
)

net start sppsvc /y %nul%

call :at_permcheck Office
if defined _perm (
echo Office 已永久激活，令牌重建可能会停用它，因此跳过……
goto :at_back
)

if %winbuild% LSS 10240 (
call :at_permcheck Windows
if defined _perm (
echo Windows 已永久激活，令牌重建可能会停用它，因此跳过……
goto :at_back
)
)

set token=
for %%# in (
%Systemdrive%\Windows\System32\spp\store_test\2.0\tokens.dat
%Systemdrive%\Windows\System32\spp\store\tokens.dat
%Systemdrive%\Windows\System32\spp\store\2.0\tokens.dat
%Systemdrive%\Windows\ServiceProfiles\NetworkService\AppData\Roaming\Microsoft\SoftwareProtectionPlatform\tokens.dat
) do if exist %%# set token=%%#

echo %line%
echo:
call :_color %Gray% "正在重建 SoftwareProtectionPlatform tokens.dat"
echo %line%
echo:

if not exist "%token%" (
%eline%
echo tokens.dat 文件没有找到。
echo 请重新启动操作系统再试一次。
goto :at_back
) else (
echo 检测到 tokens.dat 文件 [%token%]
)

echo 正在停止 sppsvc 服务……
call :_stopservice sppsvc

::  不会删除 data.dat 和缓存文件，因为这样做可能会破坏 Office 许可证，且只有重新安装才能修复

del /f /q %token% %nul%
if exist %token% (
call :_stopservice sppsvc
del /f /q %token% %nul%
)

echo:
if exist %token% (
call :_color %Red% "tokens.dat 文件删除失败。"
) else (
echo tokens.dat 文件已成功删除。
)

echo:
echo 重新安装系统许可证 [slmgr /rilc]……
cscript //nologo %windir%\system32\slmgr.vbs /rilc %nul% && (
echo [成功]
) || (
call :_color %Red% "[失败]"
)

echo:
if exist %token% (
call :_color %Green% "tokens.dat 文件已成功重建。"
) else (
call :_color %Red% "tokens.dat 文件重建失败。"
)

goto :at_back

:at_permcheck

set _perm=
if %winbuild% LSS 22483 wmic path %slp% where (LicenseStatus='1' and GracePeriodRemaining='0' and PartialProductKey is not NULL) get Name /value 2>nul | findstr /i "%1" 1>nul && set _perm=1||set _perm=
if %winbuild% GEQ 22483 %_psc% "(([WMISEARCHER]'SELECT Name FROM %slp% WHERE LicenseStatus=1 AND GracePeriodRemaining=0 AND PartialProductKey IS NOT NULL').Get()).Name | %% {echo ('Name='+$_)}" 2>nul | findstr /i "%1" 1>nul && set _perm=1||set _perm=
exit /b

::========================================================================================================================================

:cleanclipsvc

cls
mode 98, 30
title  Clean ClipSVC Licences

if %winbuild% LSS 10240 (
%eline%
echo 检测到不受支持的操作系统版本。
echo 此命令仅 Windows 10/11 及其对应服务器版本支持……
goto :at_back
)

echo:
echo %line%
echo:
echo      注：
echo:
echo       - 清理 ClipSVC 许可证有助于解决 HWID-KMS38 激活问题。
echo:
call :_color2 %_White% "      - " %Gray% "所有已安装的 HWID-KMS38 许可证将从系统中清除。"
echo         这将从系统中删除 KMS38 许可证，但无法删除 HWID 许可证。
echo:
echo       - 在应用后，建议重新启动系统。
echo:
echo %line%
echo:
choice /C:29 /N /M ">    [9] 继续 [2] 返回 ："
if %errorlevel%==1 goto at_menu

cls
echo:

echo 正在停止 ClipSVC 服务……
call :_stopservice ClipSVC
timeout /t 2 %nul%

::  感谢 @mspaintmsi 提供此命令信息

echo:
echo 正在将命令应用于清理 ClipSVC 许可证……
echo rundll32 clipc.dll,ClipCleanUpState

rundll32 clipc.dll,ClipCleanUpState

if exist "%ProgramData%\Microsoft\Windows\ClipSVC\*.dat" del /f /q "%ProgramData%\Microsoft\Windows\ClipSVC\*.dat" %nul%

if exist "%ProgramData%\Microsoft\Windows\ClipSVC\tokens.dat" (
call :_color %Red% "[失败]"
) else (
call :_color %Green% "[成功]"
)

::  下面的注册表项（Volatile 和 Protected）是在 ClipSVC 许可证清理命令后创建的，系统重启后会
::  自动删除。需要删除才能激活系统而无需重启。

set "RegKey=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ClipSVC\Volatile\PersistedSystemState"

call :regown "%RegKey%" %nul%
reg delete "%RegKey%" /f %nul%

echo:
echo 正在删除 Volatile 和 Protected 注册表项……
echo [%RegKey%]
reg query "%RegKey%" %nul% && (
call :_color %Red% "[失败]"
echo 请重新启动系统，这将会自动删除此注册表项。
) || (
call :_color %Green% "[成功]"
)

echo:
echo 正在重新启动 [ClipSVC wlidsvc LicenseManager sppsvc] 服务……
for %%# in (ClipSVC wlidsvc LicenseManager sppsvc) do (net stop %%# /y %nul% & net start %%# /y %nul%)

::========================================================================================================================================

:at_back

echo:
echo %line%
echo:
call :_color %_Yellow% "请按任意键返回……"
pause >nul
goto :at_menu

::========================================================================================================================================

:at_done

echo:
echo 请按任意键退出脚本……
pause >nul
exit /b

::========================================================================================================================================

:_stopservice

for %%# in (%1) do (
sc query %%# | find /i "STOPPED" %nul% || net stop %%# /y %nul%
sc query %%# | find /i "STOPPED" %nul% || sc stop %%# %nul%
)
exit /b

::========================================================================================================================================\

::  递归设置注册表所有权和权限的简洁而平均的片段
::  由 @AveYo 由 @BAU 编写
::  pastebin.com/XTPt0JSC

::  由 @abbodi1406 修改，使其在仅安装 x86 版本的 PowerShell 的 ARM64 Windows 10（版本早于 21277）中工作。

:regown

%_psc% $A='%~1','%~2','%~3','%~4','%~5','%~6';iex(([io.file]::ReadAllText('!_batp!')-split':Own1\:.*')[1])&exit/b:Own1:
$D1=[uri].module.gettype('System.Diagnostics.Process')."GetM`ethods"(42) |where {$_.Name -eq 'SetPrivilege'} #`:no-ev-warn
'SeSecurityPrivilege','SeTakeOwnershipPrivilege','SeBackupPrivilege','SeRestorePrivilege'|foreach {$D1.Invoke($null, @("$_",2))}
$path=$A[0]; $rk=$path-split'\\',2; switch -regex ($rk[0]){'[mM]'{$hv=2147483650};'[uU]'{$hv=2147483649};default{$hv=2147483648};}
$HK=[Microsoft.Win32.RegistryKey]::OpenBaseKey($hv, 256); $s=$A[1]; $sps=[Security.Principal.SecurityIdentifier]
$u=($A[2],'S-1-5-32-544')[!$A[2]];$o=($A[3],$u)[!$A[3]];$w=$u,$o |% {new-object $sps($_)}; $old=!$A[3];$own=!$old; $y=$s-eq'all'
$rar=new-object Security.AccessControl.RegistryAccessRule( $w[0], ($A[5],'FullControl')[!$A[5]], 1, 0, ($A[4],'Allow')[!$A[4]] )
$x=$s-eq'none';function Own1($k){$t=$HK.OpenSubKey($k,2,'TakeOwnership');if($t){0,4|%{try{$o=$t.GetAccessControl($_)}catch{$old=0}
};if($old){$own=1;$w[1]=$o.GetOwner($sps)};$o.SetOwner($w[0]);$t.SetAccessControl($o); $c=$HK.OpenSubKey($k,2,'ChangePermissions')
$p=$c.GetAccessControl(2);if($y){$p.SetAccessRuleProtection(1,1)};$p.ResetAccessRule($rar);if($x){$p.RemoveAccessRuleAll($rar)}
$c.SetAccessControl($p);if($own){$o.SetOwner($w[1]);$t.SetAccessControl($o)};if($s){$($subkeys=$HK.OpenSubKey($k).GetSubKeyNames()) 2>$null;
foreach($n in $subkeys){Own1 "$k\$n"}}}};Own1 $rk[1];if($env:VO){get-acl Registry::$path|fl} #:Own1: lean & mean snippet by AveYo

::========================================================================================================================================

:_color

if %_NCS% EQU 1 (
echo %esc%[%~1%~2%esc%[0m
) else (
call :batcol %~1 "%~2"
)
exit /b

:_color2

if %_NCS% EQU 1 (
echo %esc%[%~1%~2%esc%[%~3%~4%esc%[0m
) else (
call :batcol %~1 "%~2" %~3 "%~4"
)
exit /b

::=======================================

:: 使用纯批处理方法的彩色文本
:: 感谢 @dbenham 和 @jeb
:: stackoverflow.com/a/10407642

:batcol

pushd %_coltemp%
if not exist "'" (<nul >"'" set /p "=.")
setlocal
set "s=%~2"
set "t=%~4"
call :_batcol %1 s %3 t
del /f /q "'"
del /f /q "`.txt"
popd
exit /b

:_batcol

setlocal EnableDelayedExpansion
set "s=!%~2!"
set "t=!%~4!"
for /f delims^=^ eol^= %%i in ("!s!") do (
  if "!" equ "" setlocal DisableDelayedExpansion
    >`.txt (echo %%i\..\')
    findstr /a:%~1 /f:`.txt "."
    <nul set /p "=%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%"
)
if "%~4"=="" echo(&exit /b
setlocal EnableDelayedExpansion
for /f delims^=^ eol^= %%i in ("!t!") do (
  if "!" equ "" setlocal DisableDelayedExpansion
    >`.txt (echo %%i\..\')
    findstr /a:%~3 /f:`.txt "."
    <nul set /p "=%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%%_BS%"
)
echo(
exit /b

::=======================================

:_colorprep

if %_NCS% EQU 1 (
for /F %%a in ('echo prompt $E ^| cmd') do set "esc=%%a"

set     "Red="41;97m""
set    "Gray="100;97m""
set   "Black="30m""
set   "Green="42;97m""
set    "Blue="44;97m""
set  "Yellow="43;97m""
set "Magenta="45;97m""

set    "_Red="40;91m""
set  "_Green="40;92m""
set   "_Blue="40;94m""
set  "_White="40;37m""
set "_Yellow="40;93m""

exit /b
)

for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "_BS=%%A %%A"
set "_coltemp=%SystemRoot%\Temp"

set     "Red="CF""
set    "Gray="8F""
set   "Black="00""
set   "Green="2F""
set    "Blue="1F""
set  "Yellow="6F""
set "Magenta="5F""

set    "_Red="0C""
set  "_Green="0A""
set   "_Blue="09""
set  "_White="07""
set "_Yellow="0E""

exit /b

::========================================================================================================================================