2

I want to pass variables from VBScript to batch but it wouldn't work.

My VBScript:

Dim shell  
Set shell = CreateObject("WScript.Shell")
strnaam = InputBox ("naam")

and my batch:

@echo off
cls
echo %strnaam%
pause

I want the variable strnaam from my VBScript to my batch.

Ansgar Wiechers
  • 175,025
  • 22
  • 204
  • 278
  • 3
    VBScript and batch are running in separate processes and thus cannot share internal variables. There might be ways to sort-of do what you want (e.g. using environment variables), but you need to provide more information about how the 2 scripts are related to each other and how they're being run. – Ansgar Wiechers Apr 10 '19 at 08:42

2 Answers2

3

The most obvious way would be to run the as a For /F command and save its returned output as a variable:

@Echo Off

:NaamBox
Set "naam="
(Echo WScript.Echo InputBox("Naam:"^))>"%TEMP%\naam.vbs"
For /F Delims^=^ EOL^= %%A In ('CScript //NoLogo "%TEMP%\naam.vbs"')Do Set "naam=%%A"
If Not Defined naam GoTo NaamBox
Del "%TEMP%\naam.vbs"

Echo Uw naam is %naam%
Pause

If you don't like the idea of writing, running, then deleting the file, you could also embed your VBScript within the batch file:

<!-- :
@Echo Off
Echo Typ gelieve uw naam in de popup doos en OK te selecteren
For /F Delims^=^ EOL^= %%A In ('CScript //NoLogo "%~f0?.wsf"')Do Set "naam=%%A"
If Defined naam Echo Uw naam is %naam%&Pause
Exit /B
-->
<Job><Script Language="VBScript">
    WScript.Echo InputBox("Naam:")
</Script></Job>
Compo
  • 30,301
  • 4
  • 20
  • 32
1

You can pass the variables only via environment variables:

  1. The create_variable.vbs file:
Dim WshShell, WshEnv
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("USER") ' can be either SYSTEM, USER, VOLATILE OR PROCESS
' current value
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
WshEnv("NAAM") = "This text will appear in batch"
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
Set WshEnv = Nothing
Set WshShell = Nothing
  1. Then the batch file show_vbs_variable.bat (you have to open a new cmd.exe to have the new variable there! If you need more infor here is a topic on SO that covers it.:
@echo off
cls
echo %naam%
pause
  1. vbs script for clearing up the variable clearing_variable.vbs:
Dim WshShell, WshEnv
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("USER") ' can be either SYSTEM, USER, VOLATILE OR PROCESS
' current value
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
'Deleting the env variable
WshEnv.Remove("NAAM")
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
Set WshEnv = Nothing
Set WshShell = Nothing
tukan
  • 13,399
  • 1
  • 15
  • 39