2019年8月5日 星期一

Batch script to find and delete registry keys and/or values

You can use a batch file with a single command line for this task:
@for %%I in ("tasksche" "Other Value" "One More Value") do @%SystemRoot%\System32\reg.exe delete "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "%%~I" /f 2>nul
The internal command FOR runs external command REG for each string specified in parentheses which deletes the registry value from specified registry key.
REG would output an error message if the value to delete or the registry key itself does not exist. But this error message written to STDERR is redirected to device NUL to suppress it.
This single line batch file can be extended to read the registry values to delete from a text file and additionally output which registry value were found and successfully deleted.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "CreatedListFile="
set "ListFile=%TEMP%\ListFile.txt"

if not exist "%ListFile%" (
    set "CreatedListFile=1"
    (
        echo tasksche
        echo Other Value
        echo "One More Value"
    ) >"%ListFile%"
)

for /F "usebackq delims=" %%I in ("%ListFile%") do (
    %SystemRoot%\System32\reg.exe delete "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "%%~I" /f 2>nul
    if not errorlevel 1 echo Deleted "%%~I" from HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
)

if defined CreatedListFile del "%ListFile%"
endlocal
Of course it is possible to run multiple reg delete in the command block executed by FOR. But please note that using reg delete for deletion of a value or key in HKLM requires administrative privileges, i.e. the batch file must be executed as administrator.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
  • del /?
  • echo /?
  • endlocal /?
  • if /?
  • for /?
  • reg /?
  • reg delete /?
  • set /?
  • setlocal /?
Read also the Microsoft article about Using Command Redirection Operators explaining > used to create the list file and 2>nul used to suppress the error message.

沒有留言:

張貼留言