windowscmdregistryenvironment-variables

Deleting environment variables doesn't work


Why deleting an environment variable with reg delete HKCU\Environment /F /V TestVar in Windows 7 Professional removes it from the registry, but the variable still exists?

Here are the details: I created the following 3 .cmd files:

Check variable.cmd

echo TestVar = %TestVar%
pause

Set variable.cmd

setx TestVar 123
pause

Delete variable.cmd

reg delete HKCU\Environment /F /V TestVar
pause

Then I follow these steps (double clicking to make sure that I start a new session every time):

  1. Double click on Check variable.cmd and I see that TestVar does not exist
  2. Double click on Set variable.cmd and it says SUCCESS: Specified value was saved.
  3. Double click on Check variable.cmd and it shows the variable value. Good!
  4. Double click on Delete variable.cmd and it says The operation completed successfully.
  5. Double click on Check variable.cmd and it still shows the variable value. Bad!
  6. Click on the Start menu, type environment, click on Edit environment variables for your account to open the Environment Variables dialog box, click OK without changing anything
  7. Double click on Check variable.cmd and the variable does not exist anymore

I can find the value in the registry after step 2, I cannot find it after step 4, but step 5 still finds it. And even if I don't change anything, step 6 really deletes the variable.


Solution

  • Here is the solution to my problem. I don't know if it is the correct solution, but it works for me:

    Check variable.cmd

    set TestVar
    @pause
    

    Set variable.cmd

    setx TestVar 123
    @pause
    

    Delete variable.cmd

    reg delete HKCU\Environment /F /V TestVar
    setx DummyVarUsedToDelete ""
    reg delete HKCU\Environment /F /V DummyVarUsedToDelete
    @pause
    

    setx cannot be used to delete a variable, as explained here, but it does the missing broadcasting after a variable has been removed from the registry with reg delete.

    EDIT

    I added a line to delete the DummyVarUsedToDelete from the registry. This will not be broadcasted, but it is a small temporary problem.