您好我在将参数通过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
我如何传递参数?我已经搜索了但是我无法想出任何对我有用的东西,我会在运行它时遇到错误或参数无法通过。
答案 0 :(得分: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
请注意,我假设你需要传递带有双引号的Argument D,所以我已经包含了那些。在字符串内部,VBScript将用双引号替换双引号。如果它不起作用,请将WshShell.Run更改为wscript.echo,您应该确切地看到VBScript正在尝试传递的内容。如果不太正确,请调整它并使用WshShell.Run重试。
祝你好运。答案 1 :(得分:1)
如果你以更系统的方式解决构建复杂命令行的问题,那么你需要更少的运气:
<强> checkdir.bat:强>
@echo off
echo '%1' '%2' > checkdir.log
<强> check.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"'
(保留“引语对我来说意外”)