是否存在与VBScript等效的%*(批处理文件)或$*(bash脚本)参数列表?

我想检索确切的命令行调用。

人为的例子:

cscript //nologo script.vbs /arg1:a -s "a b" 1 c /arg2:"x y" "d e" -l '3 4'


应该返回:

/arg1:a -s "a b" 1 c /arg2:"x y" "d e" -l '3 4'


(包括引号)。

我看过WScript.Arguments,但是它不返回逐字记录命令行。

最佳答案

在VBScript中没有与%*$*等效的内容。 WScript.Arguments集合隐藏了输入命令行,从而可以将参数作为集合内的项进行访问。

我知道检索所需信息的唯一方法是查询WMI当前进程,并从进程信息中读取命令行。

这将为您提供用于启动当前脚本的完整命令行。

Option Explicit

' We need a child process to locate the current script.
Const FLAG_PROCESS = "winver.exe"

' WMI constants
Const wbemFlagForwardOnly = 32

' Generate a unique value to be used as a flag
Dim guid
    guid = Left(CreateObject("Scriptlet.TypeLib").GUID,38)

' Start a process using the indicated flag inside its command line
    WScript.CreateObject("WScript.Shell").Run """" & FLAG_PROCESS & """ " & guid, 0, False

' To retrieve process information a WMI reference is needed
Dim wmi
    Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

' Query the list of processes with the flag in its command line, retrieve the
' process ID of its parent process ( our script! ) and terminate the process
Dim colProcess, process, myProcessID
    Set colProcess = wmi.ExecQuery( _
        "SELECT ParentProcessID From Win32_Process " & _
        "WHERE Name='" & FLAG_PROCESS & "' " & _
        "AND CommandLine LIKE '%" & guid & "%'" _
        ,"WQL" , wbemFlagForwardOnly _
    )
    For Each process In colProcess
        myProcessID = process.ParentProcessID
        process.Terminate
    Next

' Knowing the process id of our script we can query the process list
' and retrieve its command line
Dim commandLine
    set colProcess = wmi.ExecQuery( _
        "SELECT CommandLine From Win32_Process " & _
        "WHERE ProcessID=" & myProcessID _
        ,"WQL" , wbemFlagForwardOnly _
    )
    For Each process In colProcess
        commandLine = process.CommandLine
    Next

' Done
    WScript.Echo commandLine

09-07 09:34