variablesvbscripthta

VBScript - Pass argument to HTA


I am working on some scripting in VBScript, I need to pass some variable values along to a HTA I am going to use as a front end to show an update is taking place.

How would I do that?

VBScript-------

TestVar1 = "Something 1"
TestVar2 = "Something 2"

wshShell.Run "Updater.hta " & TestVar1 & TestVar2

Then

HTA------- 

TestVar1 = Something.Arguments(0)
TestVar2 = Something.Arguments(1)

Msgbox TestVar1
Msgbox TestVar2

I realise thats not exactly correct code, I am just placing it to illustrate what I am attempting to do.

Any help you guys can provide in solving this would be great, thanks!


Solution

  • Enclose your parameters in quotes. Since VBScript uses " for string literals, you need to escape it by doubling it "" or you can use the Chr() function to specify the quote character:

    TestVar1 = "Something 1"
    TestVar2 = "Something 2"
    
    Dim strParams
    strParams = strParams & " " & Chr(34) & TestVar1 & Chr(34)
    strParams = strParams & " " & Chr(34) & TestVar2 & Chr(34)
    
    wshShell.Run "updater.hta" & strParams
    

    In your HTA, the Arguments collection is not available. Instead, you have to parse the CommandLine property of the HTA object. In this case, the CommandLine received by your HTA would look like the following:

    "updater.hta" "Something 1" "Something 2"
    

    So you have two options to retrieve your arguments. You can use a regex to grab everything within quotes, or you can Split() the CommandLine on quotes. If you have quotes within one of your parameters, things get trickier and you may want to consider using a different character for enclosing your parameters.

    Here's a skeleton HTA that uses Split() to extract the arguments:

    <head>
        <HTA:APPLICATION
            ID="myhta" 
            APPLICATIONNAME="HTA Test"
        >
    </head>
    
    <script language="VBScript">
        Sub Window_OnLoad()
            a = Split(myhta.CommandLine, Chr(34))
            MsgBox "Arg 1 = " & a(3)
            MsgBox "Arg 2 = " & a(5)
        End Sub
    </script>
    

    When you use Split(), you'll get something like the following:

    a = Split(myhta.CommandLine, Chr(34))
    ' a(0) = <blank>
    ' a(1) = "updater.hta"
    ' a(2) = " "
    ' a(3) = "Something 1"
    ' a(4) = " "
    ' a(5) = "Something 2"
    ' a(6) = <blank>
    

    So a(3) becomes your first argument and a(5) becomes your second.

    If you want to use a regex, it becomes:

    Sub Window_OnLoad()
    
        With New RegExp
            .Global = True
            .Pattern = """([^""]+)"""
            Set c = .Execute(myhta.CommandLine)
        End With
    
        For i = 1 To c.Count - 1        ' Skip i = 0 (the HTA filename)
            MsgBox "Arg " & i & " = " & c(i).SubMatches(0)
        Next
    
    End Sub
    

    This would display:

    Arg 1 = Something 1
    Arg 2 = Something 2