Windows有setx命令:

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

所以你可以这样设置一个变量:

setx FOOBAR 1

你可以像这样清除这个值:

setx FOOBAR ""

但是,该变量不会被删除。它保留在注册表中:

那么如何移除变量呢?


当前回答

在PowerShell中,删除注册表值的方法是使用Remove-ItemProperty cmdlet。在这种情况下,持久化值(用于将来的进程)被删除:

Remove-ItemProperty HKCU:\Environment FOOBAR

如果你想从当前环境中删除它,你可以像这样从Env: "drive"中删除它:

rm env:\FOOBAR

不能使用SETX.exe来执行此操作。

其他回答

你也可以创建一个小的VBScript脚本:

Set env = CreateObject("WScript.Shell").Environment("System")
If env(WScript.Arguments(0)) <> vbNullString Then env.Remove WScript.Arguments(0)

然后将其命名为%windir%\System32\cscript.exe //Nologo "script_name。根据“FOOBAR。

缺点是需要额外的脚本,但不需要重新启动。

setx FOOBAR ""

只是导致FOOBAR的值为空字符串。(虽然,它显示的是带有""的set命令,所以可能双引号是字符串。)

我使用:

set FOOBAR=

然后FOOBAR就不再列在set命令中了。(不需要注销。)

Windows 7 32位,使用命令提示符,非管理员是我使用的。(不是cmd或Windows + R,这可能是不同的。)

顺便说一句,我没有看到我在注册表的任何地方创建的变量,我创建了它。我使用RegEdit而不是管理员。

顺便说一下,我刚刚算出了如何用setx取消设置的永久变量。

简单地写引号,比如:

setx myvar ""

并在下一个cmd窗口重新启动,如果你搜索变量

set myvar

不会有任何安排。

不重启删除

OP的问题确实已经得到了广泛的回答,包括如何避免通过powershell、vbscript或任何你能想到的重新启动。

然而,如果你需要坚持只使用cmd命令,并且没有能够调用powershell或vbscript的奢侈,你可以使用以下方法:

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

所以这里的神奇之处在于,通过使用“setx”将一些东西分配给一个你不需要的变量(在我的例子中是DUMMY),你可以强制Explorer.exe从注册表中重新读取变量,而不需要powershell。然后你清理这个假人,尽管它会在“探索者”的环境中停留一段时间,但它可能不会伤害任何人。

或者如果在删除变量后你需要设置新的变量,那么你甚至不需要任何dummy。只要使用SETX来设置新变量,就会自动清除你刚刚从任何可能启动的新cmd任务中删除的那些变量。

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.

DougWare回答中的命令并没有起作用,但这个却起了作用:

reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v FOOBAR /f

快捷方式HKLM可用于HKEY_LOCAL_MACHINE。