当变量是参数时,VBS脚本没有输出,但在变量是硬编码时正确输出

时间:2014-07-07 19:23:14

标签: vbscript drag-and-drop arguments

这很奇怪: 当textFile是硬编码时,双击[输出(拆分)弧文件]运行时,脚本运行正常。 将文件拖放到脚本上时,没有错误,也没有输出文件。 使用拖放时脚本肯定会运行,我在writeTo之前的行中添加了一个简单的消息框,以确认它确实达到了这一点。 拖放时没有文件输出,只有当textFile被硬编码时才能正常工作。 有人请帮忙!

if WScript.Arguments.Count <> 0 then

    textFile = WScript.Arguments(0)

else

    textFile = "multi2.txt"

end if


saveTo = ""
writeTo = ""
strNewLine = "%_N_"
headingPattern = "(%_N_)"

dim fileFrom, regex, fileTo
Set fso = CreateObject("Scripting.FileSystemObject")

set fileFrom = fso.OpenTextFile(textFile)
set regex = new RegExp
set fileTo = nothing


with regex
    .Pattern = headingPattern
    .IgnoreCase = false
    .Global = true
end with

while fileFrom.AtEndOfStream <> true
    line = fileFrom.ReadLine
    set matches = regex.Execute(line)
    if matches.Count > 0 then

        strCheckForString = UCase("%")
        strNewLine = "%_N_"

        StrContents = Split(fso.OpenTextFile(textFile).ReadAll, vbNewLine)
        If (Left(UCase(LTrim(line)),Len(strCheckForString)) = strCheckForString) Then
            line = Right(line, len(line)-4)
            line1 = Left(line, len(line)-4)
            writeTo = saveTo & (line1 & ".arc")
            if not(fileTo is nothing) then fileTo.Close()
                set fileTo = fso.CreateTextFile(writeTo)
                fileTo.WriteLine(strNewLine & line)
        else
            fileTo.WriteLine(line)
        End If
    else
        fileTo.WriteLine(line)
    end if
wend

fileFrom.Close()

set fileFrom = nothing
set fso = nothing
set regex = nothing

文本文件如下所示:

%_N_160_SP01_MPF
;$PATH=/_N_WKS_DIR/_N_AFO160_WPD
blah blah blah




%_N_160_SP02_MPF
;$PATH=/_N_WKS_DIR/_N_AFO160_WPD
blah blah blah




%_N_160_SP99_MPF
;$PATH=/_N_WKS_DIR/_N_AFO160_WPD
blah blah blah

1 个答案:

答案 0 :(得分:5)

您正在生成输出文件,但不是您认为的位置。由于您没有指明生成文件的位置,因此它们是在&#34;当前目录&#34; 中为已启动的脚本进程生成的。而这个&#34;当前目录&#34; 并不总是相同的:

  • 如果双击.vbs文件,该操作的当前目录就是脚本所在的文件夹。

  • 如果将文件拖放到.vbs文件上,则当前目录是处理放置操作的资源管理器实例的当前活动目录。请注意,此目录不是资源管理器窗口显示的目录,而是explorer.exe进程的活动目录(通常为%systemroot%\system32,但可以更改)

您必须确定文件的位置,并在创建文件时明确指出。

因此,如果您需要在.vbs文件夹中创建的文件,请使用

writeTo = fso.BuildPath( _ 
    fso.GetFile( WScript.ScriptFullName ).ParentFolder.Path _ 
    , saveTo & (line1 & ".arc") _ 
)

如果您需要在输入文件所在的同一文件夹中创建的文件,请使用

writeTo = fso.BuildPath( _ 
    fso.GetFile( textFile ).ParentFolder.Path _ 
    , saveTo & (line1 & ".arc") _ 
)

或明确指出创建文件的位置。