如何在vbs中设置可在调用批处理脚本中读取的环境变量

时间:2010-09-17 17:54:51

标签: vbscript

我有一个调用vbscript文件的批处理文件。我试图让vbscript文件更改一个环境变量,该变量稍后在调用vbscript文件的批处理文件中使用。

以下是文件中的代码段。

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"

5 个答案:

答案 0 :(得分:6)

你做不到。进程可以将环境变量传递给子进程,但不能传递给它的父进程 - 在这种情况下,父进程是cmd.exe,它运行的是Parent.bat文件。

当然还有其他方法可以将信息传回父级批处理文件 - 输出到stdout或文件是一种显而易见的方式,例如。

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

== Parent.cmd ===
for /f "tokens=*" %%i in ('cscript //nologo child.vbs') do set Value=%%i
echo %Value%

答案 1 :(得分:2)

是的,你可以......但是,你必须在你的会话中重置vv。请参阅以下链接:

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

我就这样做了:

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

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

然后在一个单独的VB脚本(resetvars.vbs)中,我从CMD脚本调用:

cscript //nologo \\%APPSERVER%\apps\IE9.0\restartvars.vbs   
call %TEMP%\resetvars.bat

答案 2 :(得分:0)

我认为你不能这样做。至少,你需要在调用过程中弄乱环境块,并且无法保证它会尊重这个......

答案 3 :(得分:0)

关于这个问题:

@echo off
set vbsFile=%temp%\createguid.vbs
call :CreateVbs
call :GetGuid NewGuid
echo.%NewGuid%
del %vbsFile%>nul
GOTO:EOF

:CreateVbs
echo.set obj = CreateObject("Scriptlet.TypeLib")>%vbsFile%  
echo.WScript.StdOut.WriteLine obj.GUID>>%vbsFile% 
GOTO:EOF

:GetGuid
for /f "tokens=*" %%i in ('cscript //nologo %vbsFile%') do set %1=%%i
GOTO:EOF

这不是纯粹的批处理脚本,但可以正常工作。

答案 4 :(得分:0)

@echo off&color 4a&title %~n0&AT>NUL
IF %ERRORLEVEL% EQU 0 (
    goto 2
) ELSE (
    echo.
)
if not "%minimized%"=="" goto 1
set minimized=true & start /min cmd /C "%~dpnx0"&cls&exit
:1
wmic process where name="cmd.exe" CALL setpriority "realtime">nul&echo set shell=CreateObject("Shell.Application") > %~n0.vbs&echo shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1 >> %~n0.vbs&echo set shell=nothing >> %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit
:2
echo %~dpnx0 admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"&timeout 3 /NOBREAK>nul
:3
echo x=msgbox("end of line" ,48, "%~n0") > %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit