Getting environment varibles from cmd file

  • Thread starter Thread starter BrianB
  • Start date Start date
B

BrianB

I have a VB.NET application that needs to extract the environment variables
(EV) set by a bat file named SetVars.cmd. I would think the easiest way
would be to have my VB run the cmd file and then just read the environment
variables that are set. But I haven't found a way to do that. It appears
that the cmd file runs as its own process and the EV that are set are
promptly forgotten as soon as the cmd file finishes. For my test the cmd
file contains one line:

set myjunk=v1.2.3.4

The VB.net code that I've tried follows. Neither returns the value set in
the cmd file. Any suggestions how I can do this would be greatly
appreciated.

wsh = CreateObject("WScript.Shell")
wsh.Run(.CollectionFolder & "\SetVars.cmd", 0, 1)
MsgBox("EV = " & Environment.GetEnvironmentVariable("myjunk"))

startInfo = New System.Diagnostics.ProcessStartInfo(.CollectionFolder &
"\SetVars.cmd")
pStart.StartInfo = startInfo
pStart.Start()
pStart.WaitForExit()
MsgBox("EV = " & Environment.GetEnvironmentVariable("myjunk"))

Brian
 
It appears
that the cmd file runs as its own process and the EV that are set are
promptly forgotten as soon as the cmd file finishes.

You are right. The CMD process inherits EVs from the system once it is
started, and keeps its own copy. Once the process ends, that copy is
disposed of.

If, however, the CMD process changes the EV and then launches a new
process, that new process inherits CMD's current EVs.

Can you flip the logic around, and have the batch file launch the VB
app in stead?
 
Thank you, RoRo. Unfortunately I cannot flip them. The cmd file is created
by and used by another application and I just have the authority to read it.

Well I suppose that I can parse the cmd file looking for "set" commands and
make them EVs within VB.

Brian
 
Well I suppose that I can parse the cmd file looking for "set" commands and
make them EVs within VB.

That will work if you can assume the "set" statements are simple.
Since NT4, "set" is quite powerful. It supports math, substring
handling, search/replace and so on. Implementing these things would be
a lot of work.

I just thought of a possible trick: When a batch file launches another
batch file, CMD executes both batch files in the same environment.

If you make your own bat file, which works as a "wrapper", you could
simply have that bat echo the EVs, which is simple to capture. Your
wrapper batch would look like this:

@echo off
call c:\somedir\target.bat
echo %variablename%
 
BrianB said:
Thank you, RoRo. Unfortunately I cannot flip them. The cmd file is
created by and used by another application and I just have the
authority to read it.
Well I suppose that I can parse the cmd file looking for "set"
commands and make them EVs within VB.

You could read the cmd file and write out another with the call to your
program at the end of it...
 
Back
Top