VBScript - no access to text file unless Wscript.Sleep, even though the file is already available

StackOverflow https://stackoverflow.com/questions/23454460

  •  15-07-2023
  •  | 
  •  

Question

I'm still not too experienced with VBScript, so I probably made some rookie mistakes I just don't see, yet. What I'm basically trying to do is a workaround for getting the clients license information for MS Office 2013 via a vbscript. It's dumping the license information from the ospp.vbs file in the Office folder into a txt file.

Here's an abridged part of my script, that shows the problem:

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

Running it like this throws the error Input past end of file (800A003E) for the line:

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

If I uncomment the Wscript.Sleep 4000, it works fine and shows the expected result. Why does it throw the error, even though I put in the Do-Loop to wait for the file to actually exist?

Was it helpful?

Solution

The .Run method has a parameter

bWaitOnReturn

Optional. Boolean value indicating whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).

Use that to make sure that tmpOutput.txt is completely written and closed before the .ReadAll().

Untested speculation: The error "input past end" means that the file exists (that's all what you check for) but has no content yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top