如果您以更系统的方式解决构建复杂命令行的问题,则需要更少的运气:
检查目录.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"'
(保留 " 引号让我感到惊讶)