VBScript - 除非Wscript.Sleep,否则无法访问文本文件,即使文件已经可用

时间:2014-05-04 09:08:14

标签: vbscript

我对VBScript仍然没有太多经验,所以我可能犯了一些我还没看到的新手错误。 我基本上要做的是通过vbscript获取MS Office 2013的客户端许可证信息的解决方法。 它将许可信息从Office文件夹中的ospp.vbs文件转储到txt文件中。

这是我的脚本的一个简略部分,它显示了问题:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = Wscript.CreateObject("WScript.Shell")
Dim IsThere
If objFSO.fileExists("C:\Program Files\Microsoft Office\Office15\OSPP.VBS") Then
            isThere = True
            objShell.Run "cmd /K cscript ""C:\Program Files\Microsoft Office\Office15\OSPP.VBS"" /dstatus > C:\temp\tmpOutput.txt & exit"
    ElseIf objFSO.fileExists("C:\Program Files (x86)\Microsoft Office\Office15\OSPP.VBS") Then
        isThere = True
        objShell.Run "cmd /K cscript ""C:\Program Files (x86)\Microsoft Office\Office15\OSPP.VBS"" /dstatus > C:\temp\tmpOutput.txt & exit"
    End If
    ' wait for ospp.vbs zu finish and create the temporary txt file with license information
    Do While Not objFSO.fileExists("C:\temp\tmpOutput.txt")
        Wscript.Sleep 10
    Loop
    If isThere = True AND objFSO.fileExists("C:\temp\tmpOutput.txt") Then
    'Wscript.Sleep 4000
        Dim listFile
        listFile = objFSO.OpenTextFile("C:\temp\tmpOutput.txt").ReadAll
        Wscript.Echo listFile
    End If
    ' Delete temporary data file
    If objFSO.fileExists("C:\temp\tmpOutput.txt") Then
        objFSO.deleteFile "C:\temp\tmpOutput.txt"
    End If

像这样运行会抛出错误输入文件末尾(800A003E)的行:

listFile = objFSO.OpenTextFile("C:\temp\tmpOutput.txt").ReadAll

如果我取消注释 Wscript.Sleep 4000 ,它可以正常工作并显示预期结果。 为什么它会抛出错误,即使我放入Do-Loop等待文件实际存在?

1 个答案:

答案 0 :(得分:1)

.Run方法有参数

  

bWaitOnReturn

     

可选。布尔值,指示脚本是否应该等待程序   在继续下一个之前完成执行   脚本中的语句。如果设置为true,则脚本执行将停止,直到   程序完成,Run返回由...返回的任何错误代码   程序。如果设置为false(默认值),则返回Run方法   启动程序后立即自动返回0(不是   被解释为错误代码)。

使用它来确保在.ReadAll()之前完全写入和关闭tmpOutput.txt。

未经测试的推测:错误"输入结束"意味着该文件存在(这是您检查的所有内容)但尚无内容。