3

您好我在通过 vbscript 将参数传递到批处理文件时遇到问题。我不太擅长编程,所以我确信我只是错过了一些愚蠢的东西。无论如何,我正在使用 vbscript 隐形运行批处理文件

vbscript 被称为"C:\Program Files (x86)\scripts\check.vbs" %S "%D"

其中 %S 是状态,%D 是目录。

如果我直接调用批处理文件,因为"C:\Program Files (x86)\scripts\checkdir.bat" %S "%D"一切正常,除了弹出一个令人讨厌的dos窗口。

于是我上网查了一下,找到了这个可以静默运行批处理文件的vbscript。它实际上会以静默方式运行它,但是它不会将参数传递给批处理文件。

这是vbscript:

Set WshShell = CreateObject("WScript.Shell") 
WshShell.Run chr(34) & "C:\Program Files (x86)\scripts\checkdir.bat" & Chr(34), 0
Set WshShell = Nothing

我将如何传递参数?我已经搜索过,但我找不到任何对我有用的东西,我要么在运行时出错,要么参数不通过。

4

2 回答 2

4

假设您以这种方式调用 VBScript ......

wscript myscript.vbs ArgumentS ArgumentD

然后为此换出第2行应该可以...

WshShell.Run """C:\Program Files (x86)\scripts\checkdir.bat"" " & WScript.Arguments.Item(0) & " """ & WScript.Arguments.Item(1) & """", 0

请注意,我假设您需要传递带有双引号的参数 D,所以我已经包含了这些。在字符串内,VBScript 将用单双引号替换双双引号。如果它不起作用,请将 WshShell.Run 更改为 wscript.echo,您应该可以准确地看到 VBScript 试图传递的内容。如果它不完全正确,请调整它并使用 WshShell.Run 重试。

祝你好运。

于 2013-05-23T19:58:06.660 回答
1

如果您以更系统的方式解决构建复杂命令行的问题,则需要更少的运气:

检查目录.bat:

@echo off
echo '%1' '%2' > checkdir.log

检查.vbs:

Option Explicit

Dim oFS  : Set oFS  = CreateObject("Scripting.FileSystemObject")
Dim oWAU : Set oWAU = WScript.Arguments.Unnamed
Dim oWS : Set oWS = CreateObject("WScript.Shell")

Dim S : S = "state"
If oWAU.Count >= 1 Then S = oWAU(0)
Dim D : D = "directory"
If oWAU.Count >= 2 Then D = oWAU(1)

Dim sBFspec : sBFSpec = oFS.GetAbsolutePathName(".\checkdir.bat")

' One way of building a command from parts that need quoting
' Replacing placeholders in a template is another one
' Everything is better than concatenating, cf:
' """C:\Program Files (x86)\scripts\checkdir.bat"" " & WScript.Arguments.Item(0) & " """ & WScript.Arguments.Item(1) & """", 0
Dim sCmd    : sCmd    = Join(Array( _
      qq(sBFSpec) _
    , qq(S) _
    , qq(D) _
))

' sanity check
WScript.Echo "About to call:"
WScript.Echo sCmd
WScript.Echo "Your last chance to check!"

Dim iRet : iRet = oWS.Run(sCmd, 0, True)
If 0 = iRet Then
   WScript.Echo "looks ok:"
   WScript.Echo oFS.OpenTextFile(".\checkdir.log").ReadAll()
Else
   WScript.Echo "looks bad:", iRet
End If

WScript.Quit 0

Function qq(s) : qq = """" & s & """" : End Function

输出:

cscript check.vbs
About to call:
"E:\trials\SoTrials\answers\16722567\vbs\checkdir.bat" "state" "directory"
Your last chance to check!
looks ok:
'"state"' '"directory"'

cscript check.vbs "i don't care" "c:\ \ \simsalabim"
About to call:
"E:\trials\SoTrials\answers\16722567\vbs\checkdir.bat" "i don't care" "c:\ \ \simsalabim"
Your last chance to check!
looks ok:
'"i don't care"' '"c:\ \ \simsalabim"'

或者:

checkdir.bat "i don't care" "c:\ \ \simsalabim"

type  checkdir.log
'"i don't care"' '"c:\ \ \simsalabim"'

(保留 " 引号让我感到惊讶)

于 2013-05-23T20:25:38.207 回答