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

后端 未结 2 1433
情话喂你
情话喂你 2020-11-29 14:25

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 pass

相关标签:
2条回答
  • 2020-11-29 14:31

    I think what you're looking for is this.

    shell.run "job.bat ""argfile.ext"" " & inp
    

    However, as Ansgar Wiechers points out, this is a potentially severe security hole, as a treacherously crafted XML file could run arbitrary commands. To encapsulate your batch file arguments and prevent unintended consequences, consider switching to the Shell.Application object's ShellExecute method.

    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
    
        set shell=CreateObject("Shell.Application") 
        shell.ShellExecute "job.bat", """a file"" " & inp, "path\to\batfile\", "runas", 1
        set shell=nothing 
    
    Next 
    
    0 讨论(0)
  • 2020-11-29 14:37

    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, "_")
    
    0 讨论(0)
提交回复
热议问题