Command line to remove an environment variable from the OS level configuration

前端 未结 9 1155
闹比i
闹比i 2020-11-30 17:11

Windows has the setx command:

Description:
    Creates or modifies environment variables in the user or system
    environment.

So you can

9条回答
  •  被撕碎了的回忆
    2020-11-30 17:44

    Delete Without Rebooting

    The OP's question indeed has been answered extensively, including how to avoid rebooting through powershell, vbscript, or you name it.

    However, if you need to stick to cmd commands only and don't have the luxury of being able to call powershell or vbscript, you could use the following approach:

    rem remove from current cmd instance
      SET FOOBAR=
    rem remove from the registry if it's a user variable
      REG delete HKCU\Environment /F /V FOOBAR
    rem remove from the registry if it's a system variable
      REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
    rem tell Explorer.exe to reload the environment from the registry
      SETX DUMMY ""
    rem remove the dummy
      REG delete HKCU\Environment /F /V DUMMY
    

    So the magic here is that by using "setx" to assign something to a variable you don't need (in my example DUMMY), you force Explorer.exe to reread the variables from the registry, without needing powershell. You then clean up that dummy, and even though that one will stay in Explorer's environment for a little while longer, it will probably not harm anyone.

    Or if after deleting variables you need to set new ones, then you don't even need any dummy. Just using SETX to set the new variables will automatically clear the ones you just removed from any new cmd tasks that might get started.

    Background information: I just used this approach successfully to replace a set of user variables by system variables of the same name on all of the computers at my job, by modifying an existing cmd script. There are too many computers to do it manually, nor was it practical to copy extra powershell or vbscripts to all of them. The reason I urgently needed to replace user with system variables was that user variables get synchronized in roaming profiles (didn't think about that), so multiple machines using the same windows login but needing different values, got mixed up.

提交回复
热议问题