如何通过存储在字符串中的名称来访问变量?

时间:2017-04-24 11:06:31

标签: vbscript

在下面的示例中,我想编写一个函数,用该$替换以该变量的实际内容开头的字符串。考虑到该函数将解析所有内容$somevar,因此,请不要将文字视为param1param2

Dim myCmd, param1, param2 

Const MY_CONST = "constValue"    

param1 = "myParameter1"
param2 = "myParameter2"

myCmd = "myprogram.exe $param1 $param2 $MY_CONST"
myCmd = addParams(myCmd)

Function addParams(cmdStr)

' this function should replace all "$variables" by its respective content
' Example: "myprogram.exe myParameter1 myParameter2 constValue"


End Function

2 个答案:

答案 0 :(得分:0)

我找到了解决方案。这相当于Javascript Template Literals。在使用参数组合命令行以及需要连接各种字符串和变量的情况时,它非常有用:

Sub ev(ByRef cmdStr)
    Dim rx, matches, match

    ' Replace single quotes with double quotes
    cmdStr = replace(cmdStr, "'", chr(34))

    ' Replace $variavle strings with their actual value
    Set rx = New RegExp
    rx.Global = True
    rx.pattern = "\$\w+"
    Set matches = rx.Execute(cmdStr)
    For each match in matches
        cmdStr = replace(cmdStr, match, eval( replace(match, "$", "") ))
    Next
End Sub


Const HOST = "192.168.0.1"
Dim cmd, param1, param2

param1 = "-t"
param2 = "-w 5000"
cmd = "ping $param1 $param2 $HOST"
ev cmd

wscript.echo cmd

基于Lankymart评论的更好方法:

function bind(cmdStr, arrParams)
    Dim i
    For i = 0 to uBound(arrParams)
        cmdStr = replace(cmdStr, "$"&i+1, arrParams(i))
    Next
    cmdStr = replace(cmdStr, "'", chr(34))
    bind = cmdStr
End Function


cmd = bind("program.exe --param1 '$1' --param2 '$2'", Array(myVar1, myVar2))

答案 1 :(得分:0)

要想让这个自给自足,我的尝试基于@Azevedo's answer

添加几个

  • 按顺序传递参数数组
  • 在阵列中发送空白参数会强制删除相关空间。
Function ev(cmd, params)
  Dim rx, matches, i, result
  result = cmd
  Set rx = New RegExp
  rx.Global = True
  rx.pattern = "\$\w+"
  Set matches = rx.Execute(cmd)
  If matches.Count > 0 Then
    For i = 0 To matches.Count - 1
      If IsArray(params) Then
        If Len(params(i)) > 0 Then params(i) = " " & params(i)
        result = Replace(result, " " & matches(i), params(i))
      End If
    Next
  End If
  ev = result
End Function

Const HOST = "192.168.0.1"
Dim cmd: cmd = "ping $param1 $param2 $HOST"

'Test with all parameters
WScript.Echo ev(cmd, Array("-t", "-w 5000", HOST))
'Test with missing parameter
WScript.Echo ev(cmd, Array("-t", "", HOST))
'Test with no parameters
WScript.Echo ev(cmd, Empty)

输出:

ping -t -w 5000 192.168.0.1
ping -t 192.168.0.1
ping $param1 $param2 $HOST