0

I have made a perfect square number finder that starts from 1 and the code is below. However, I need a way to pass variables between batch and vbscript (VBS has a better UI). I am stuck at this point, how do I send a variable between a batch and vbscript? If anything maybe have the vbscript print a number into a file then the batch script reads the file and the number in it then deletes it.

@echo off 
title Perfect Squares without paste to file
cls

set /a num=3
set /a num1=1
echo 1

:1
set /a num2=%num1%+%num%
echo %num2%
echo %num2%
set /a num1=%num2%
set /a num=%num%+2
goto 1
R2bEEaton
  • 29
  • 1
  • 12
  • 2
    You can use command line arguments while calling the batch files to pass on the data from VBS – Pankaj Jaju Mar 19 '15 at 21:08
  • Please show the VBS part. Not clear, please elaborate do you need to pass from batch to VBS or from VBS to batch? [This answer](https://stackoverflow.com/a/34321609/2165759) may be helpful. – omegastripes Oct 17 '17 at 16:46

1 Answers1

3

You can run a VBScript from a batch file like this (the parameter //NoLogo prevents the interpreter from printing the version/copyright banner all the time):

cscript //NoLogo C:\your.vbs 23

Use the Arguments property for receiving the argument (23) in the VBScript:

value = WScript.Arguments(0)

and pass a value back to the batch script via the return value:

WScript.Quit 42

Example:

VBScript code:

value = WScript.Arguments(0)
WScript.Quit value + 19

Batch code:

@echo off

cscript //NoLogo C:\your.vbs %1
echo %errorlevel%

Output:

C:\>batch.cmd 23
42

C:\>batch.cmd 4
23

If you need to pass text back and forth, passing the response back to the batch script becomes more complicated. You'll need something like this:

for /f "tokens=*" %%r in ('cscript //NoLogo C:\your.vbs %1') do set "res=%%r"

Example:

VBScript code:

str = WScript.Arguments(0)
WScript.StdOut.WriteLine str & " too"

Batch code:

@echo off

setlocal

for /f "tokens=*" %%r in ('cscript //NoLogo C:\your.vbs %1') do set "res=%%r"
echo %res%

Output:

C:\>batch.cmd "foo"
foo too

C:\>batch.cmd "and some"
and some too

On a more general note: why do you use batch/VBScript in the first place? PowerShell is far more versatile than both of them combined, and is available for any halfway recent Windows version.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328