开发者

VBScript : Windows System enviroment variable, changes not getting reflected in CMD prompt

I have written a VB script开发者_JAVA技巧 (.vbs) to add a Windows System Environment variable, as shown below,

set WshShell = CreateObject("WScript.Shell")
WshShell.RegWrite "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\CATALINA_HOME", "C:\Tomcat5" , "REG_EXPAND_SZ"

When I see this environment variable in System Properties -> Advanced -> Environment Variables dialog, It shows that environment variable there.

But, when I run the command prompt and type "set" command there, I don't find the variable there. (I started the new CMD prompt after execution of the VBS)

Some how CMD prompt is not getting the changes in environment variable.

If I restart the machine, then I can access the environment variable from CMD prompt. But, I don't want user to restart the system after executing my vbs and the work in cmd prompt.

Any ideas?


that is because you are "inserting" a permanent value on the registry, to set a "live" value use the flowing code, for both prouposes use both codes

  SET oShell = CREATEOBJECT("Wscript.Shell")
  SET wSystemEnv = oShell.Environment("SYSTEM")
  wSystemEnv("<Name>") = "<Value>"
  SET wSystemEnv = NOTHING
  SET oShell = NOTHING


Thanks Luis!

Actually, adding/modifying environment variable using registry is a bit raw way. We might be creating some inconsistencies by doing so.

So, the ideal way of doing is by using the collection which is dedicated to the environment variables, WshEnvironment.

Now, as suggested by Luis, I have written the following script to add system environment variable,

Set wshshell = CreateObject("WScript.Shell")
Dim WshSySEnv
Set WshSysEnv = wshshell.Environment("SYSTEM")
WshSysEnv("1VINOD") = "1Vinod"
WshSysEnv("2VINOD") = "2Vinod"
Set WshSySEnv = Nothing

Save this code in vbs file, execute the vbs file. Now, you will get the 2 environment variables in cmd prompt without restarting the system.

Similar script for removing the variables,

Set wshshell = CreateObject("WScript.Shell")
Dim WshSySEnv
Set WshSysEnv = wshshell.Environment("SYSTEM")
WshSysEnv.Remove("1VINOD") 
WshSysEnv.Remove("2VINOD") 
Set WshSySEnv = Nothing

This also does not require any restarts/logon-logoffs.

Enjoy!

I have tested it on XP, hope this works on Windows 7, too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜