Joshua Dixon
Joshua Dixon

Reputation: 45

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

I have scoured the internet for a batch file to find and delete registry keys and/or values. The closest thing I found here: Deleting all registry keys containing or named "string" with Batch.

However, I have created a regsitry key in "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", called "tasksche", updated the scripts RegKey and Search variables as such, then changed Action to Delete. It never finds and deletes it.

I have tried other methods to work this out, but nothings working.

What I am trying to write is this: Batch file reads a list of keys from a text file Batch file scans the registry for those keys and/or values Batch file deletes those keys.

Upvotes: 0

Views: 17452

Answers (1)

Mofi
Mofi

Reputation: 49084

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.

Upvotes: 2

Related Questions