开发者

Batch file to delete multiple values within a key in Registry

The following key had multiple values like "Find", "Find 0", Find 1", "开发者_运维百科Find 2" and so on. HKCU\Software\Microsoft\VisualStudio\9.0\Find

The values increase with use and I have no prior knowledge of the maximum number. Goal is to create a batch file to delete all the "Find *" values without knowing the maximum value beforehand.

I tried the following with max number = 10:

@ECHO OFF
FOR /L %%G IN (0,1,10) DO REG DELETE HKCU\Software\Microsoft\VisualStudio\9.0\Find /v "Find %%G" /f
PAUSE

How do I loop till the max number if I don't have an idea about it?

I could put a large number like 100 and loop it through. But that would be unnecessary looping.

Idea:

After it reaches the max number it throws out an error in the console

"Error:  The system was unable to find the specified registry key or value"

I would like to capture this in a variable and check for the string "Error ...." and if true, terminate the loop. I have no idea how to do this.


You'll need to replace the FOR loop with the WHILE loop.

Of course, there's no such thing as 'the WHILE loop' in batch scripting. It is usually emulated with IF and GOTO.

Here's a sample script:

@ECHO OFF
SET G=-1
SET Err=0
:loop
SET /A G+=1
REG DELETE HKCU\Software\Microsoft\VisualStudio\9.0\Find /v "Find %G%" /f || SET Err=1
IF %Err% == 0 GOTO loop
PAUSE

As you can see, the error is caught with the help of || operator. The command after || is only executed if the one before || resulted in an error. So, while the script is deleting values successfully, the Err variable remains unchanged, i.e. equal to 0, and so the subsequent IF always evaluates to TRUE and executes the GOTO accordingly.

As soon as there's an error when attempting to delete another value, the SET Err=1 command is executed and, as a consequence, we are exiting the loop.


EDIT for the change request.

To account for the Find parameter (without numbers and spaces after the name) you'll have to act a bit differently, maybe like this:

@ECHO OFF
SET G=-1
SET Err=0
:loop
IF %G% == -1 (SET ParamName="Find") ELSE (SET ParamName="Find %G%")
REG DELETE HKCU\Software\Microsoft\VisualStudio\9.0\Find /v %ParamName% /f || SET Err=1
IF %Err% == 0 (SET /A G+=1 & GOTO loop)
PAUSE
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜