Passing-variable-from-vbscript-to-batch-file with arguments

batch-filevbscript

Please how to pass the 'inp" variable from this piece of vbs to my batch named job.bat? Indeed when doing echoing (echo %2) from job.bat, i notice that the inp is not passed properly. prompt command views inp and not the value retrieved from vbs. Thanks

For Each listElement In xmlDoc.selectNodes("document/Lists/list")
 msgbox "toto"
 inp=listElement.selectSingleNode("entry").text
 out=  listElement.selectSingleNode("output").text
 jeton=  listElement.selectSingleNode("token").text

 dim shell
 set shell=createobject("wscript.shell") 
 shell.run "job.bat ""a file"" **inp** "
 set shell=nothing 
 Next 

Best Answer

Unlike several other languages VBScript doesn't expand variables inside strings. Because of that, inp in the string

"job.bat ""a file"" inp "

is just the literal string "inp", not the value of the variable inp. To produce a string with the value of a variable, you have to concatenate base string and variable like @rojo suggested:

shell.run "job.bat ""a file"" " & inp

I would, however, not recommend doing this without some safety precautions. For one thing you should always put double quotes around your arguments, in case they contain spaces. I normally use a quoting function for this to prevent the instruction from becoming riddled with quad-quotes:

Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function

'...
shell.run "job.bat " & qq("a file") & " " & qq(inp)

You should also always apply sanitizing to all user input that is passed to a shell command. Otherwise your users might wreak havoc by entering something like foo & del /s /q C:\*.*. Common practice is to allow only known-good characters in the input string and replace everything else with a safe character (e.g. an underscore). You can achieve this with a regular expression:

Set re = New RegExp
re.Pattern = "[^ a-z0-9äöü.,_$%()-]"
re.Global  = True
re.IgnoreCase = True

inp = re.Replace(inp, "_")