在 VBScript/JScript 中为控制台应用程序编写代理启动器

问题描述

我想改变一些传递给应用程序的参数,将其包装到可检查的脚本中。

CMD.exe 不在列表中,因为它破坏了原始参数列表(=,; 被视为命令分隔符,将 --opt=val 渲染为 {{1 }} + --opt).

我虽然对 JScript 感兴趣,但对 valWscript.Shell + RunExecShell.Application 创建新窗口的事实感到沮丧而不是附加到现有控制台。

包装器将 STdio 控制传递给启动的应用程序至关重要。常规批处理文件遵循这样的语义,即使通过 ShellExecute 包装器调用应用程序,CLI 管道也会继续工作。

解决方法

你在寻找这样的东西吗?

launchApplication.vbs

Dim args : args = ""
For Each arg In WScript.Arguments
    If ("" = args) Then
        args = arg
    Else
        args = args & " " & arg
    End If
Next

WScript.StdOut.WriteLine "You are using these args: " & args

Dim o,e
With WScript.CreateObject("WScript.Shell")
    With .Exec(.ExpandEnvironmentStrings("%COMSPEC% /c application.exe " & args))
        o = .StdOut.ReadAll()
        e = .StdErr.ReadAll()
    End With
End With

WScript.StdOut.WriteLine "StdOut: " & o
WScript.StdOut.WriteLine "StdErr: " & e

然后使用 cscript.exe 调用它。例如:

cscript.exe launchApplication.vbs --opt=val

假设您的控制台 application.exe 实际上接受 --opt=val,那么上面的脚本应该能够捕获用于调用 application.exe 的命令行参数,以及来自 application.exe 的 stdout 和 stderr。 exe。

如果需要,也可以在执行 application.exe 之前对其进行修改以更改命令行参数。