Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables in vbs that can be read in calling batch script

Tags:

vbscript

I have a batch file that calls a vbscript file. I am trying to have the vbscript file change an environment variable that is later used in the batch file that calls the vbscript file.

Here are snippetes from the files.

Parent.bat

Set Value="Initial Value"
cscript Child.vbs
ECHO Value = %VALUE%

Child.vbs

Set wshShell = CreateObject( "WScript.Shell" )
Set wshSystemEnv = wshShell.Environment( "Process" )
wshSystemEnv("VALUE") = "New Value"
like image 279
Josh Avatar asked Sep 17 '10 17:09

Josh


2 Answers

yes, you can.... however, you'll have to resetvars in your session. see the following link:

Is there a command to refresh environment variables from the command prompt in Windows?

'RESETVARS.vbs

Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)

set oEnv=oShell.Environment("System")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")

set oEnv=oShell.Environment("User")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)
next

path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close

This is how I did it:

SET oShell = CREATEOBJECT("Wscript.Shell") 
dim varSet
SET varSet = NOTHING 

  SET varSet = oShell.Environment("SYSTEM") 
  varSet("WinVer") = "6.0.2008"

Then in a separate VB script (resetvars.vbs) I called from CMD script:

cscript //nologo \\%APPSERVER%\apps\IE9.0\restartvars.vbs   
call %TEMP%\resetvars.bat
like image 188
tgkone Avatar answered Sep 18 '22 21:09

tgkone


You can't. A process can pass environment variables to child processes, but not to its parent - and in this case the parent is cmd.exe, which is running your Parent.bat file.

There are of course other ways to communicate information back to the parent batch file - outputting to stdout or a file is an obvious way, e.g.

== Child.vbs ===
WScript.echo "New Value"

== Parent.cmd ===
for /f "tokens=*" %%i in ('cscript //nologo child.vbs') do set Value=%%i
echo %Value%
like image 27
Joe Avatar answered Sep 16 '22 21:09

Joe