Windows CMD - 从批处理文件重置路径变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7086965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows CMD - Reset path variable from batch file?
提问by Ben
I've got a batch file that modifies the PATH
variable by prepending a few addresses. When the user logs off-then-on, PATH
is reset to its original value (before the batch file was ever run). This behavior is OK.
我有一个批处理文件,它PATH
通过添加几个地址来修改变量。当用户注销然后再登录时,PATH
将重置为其原始值(在运行批处理文件之前)。这种行为是可以的。
However, if the batch file is run more than once, the same values are re-prepended and I end up with a overly long, redundant PATH variable that just gets longer after each batch run.
但是,如果批处理文件运行不止一次,相同的值会被重新添加,我最终会得到一个过长的冗余 PATH 变量,每次批处理运行后都会变长。
I'd like to reset the variable to whatever it is when the user logs on, before the values are prepended. I figure the solution is to write the original value in a temp file and read it back, but is there a better way to do it?
我想在用户登录时将变量重置为任何值,然后再添加值。我认为解决方案是将原始值写入临时文件并将其读回,但有没有更好的方法来做到这一点?
采纳答案by Harry Johnston
Rather than writing the original value to a temp file, you could write it to another environment variable:
您可以将原始值写入另一个环境变量,而不是将原始值写入临时文件:
if not defined ORIGINAL-PATH set ORIGINAL-PATH=%PATH%
set PATH=c:\extra\stuff;%ORIGINAL-PATH%
but it would be better to explicitly check whether the string you want is in PATH already or not, like this:
但最好明确检查您想要的字符串是否已经在 PATH 中,如下所示:
echo %PATH% | findstr /c:"c:\extra\stuff;" > nul || set PATH=c:\extra\stuff;%PATH%
回答by Michael Burr
Put @SETLOCAL
at the top of your batch file.
放在@SETLOCAL
批处理文件的顶部。
Any changes made to the environment will be restored when the batch file exits.
当批处理文件退出时,将恢复对环境所做的任何更改。
Run setlocal /?
for more details.
运行setlocal /?
以获取更多详细信息。
回答by user3131978
I've been looking for a solution for long time for a similar problem. Finally I ended up using the pathmgr.cmd which I've downloaded from:
我一直在寻找类似问题的解决方案。最后我最终使用了我从以下位置下载的 pathmgr.cmd:
http://gallery.technet.microsoft.com/Batch-Script-To-Manage-7d0ef21e
http://gallery.technet.microsoft.com/Batch-Script-To-Manage-7d0ef21e
To use it to clean the user PATH, the below options can be used from command line:
要使用它来清理用户 PATH,可以从命令行使用以下选项:
pathmgr.cmd /clean /user /p /y
pathmgr.cmd /clean /user /p /y
Many other useful options are also available.
许多其他有用的选项也可用。