Search code examples
scriptingvbscriptscripting-language

VB Script does not recognize the actual parameter


I've two VB Scripts. Say First.vbs and Second.vbs.

Frist.vbs calls Second.vbs each time some action/event happens.

I am trying to send two parameters from Frist.vbs to Second.vbs using the following code:

Contents of First.vbs:

Set objShell = Wscript.CreateObject("WScript.Shell")
param1 = "Welcome"
param2 = "Gokul Nath"
objShell.Run "Second.vbs" & " " & param1 & " " & param2
Set objShell = Nothing

Contents of Second.vbs:

param1= Wscript.Arguments.Item(0)
param2 = Wscript.Arguments.Item(1)
WScript.Echo(param1)
WScript.Echo(param2)

I'm getting the following Echo messages:

Welcome - Which is correct, since I've passed "Welcome" from First.vbs
Gokul - Which is WRONG, since I've passed "Gokul Nath" from First.vbs

This issue occurs, since each space is considered as end of a parameter.

I am new to scripting, can anyone give some suggestion/reference.


Solution

  • The value of param2 contains a space and you didn't put the parameter between double quotes. Because of that your Run command-line effectively has 3 arguments:

    • Welcome
    • Gokul
    • Nath

    To avoid that add double quotes around your second argument:

    objShell.Run "Second.vbs" & " " & param1 & " """ & param2 & """"
    

    Better yet, quote all arguments and use a quoting function so you don't drown in double quotes:

    Function qq(str)
      qq = Chr(34) & str & Chr(34)
    End Function
    
    objShell.Run "Second.vbs" & " " & qq(param1) & " " & qq(param2)