VBS Run cmd.exe output to a variable; not text file

前端 未结 2 1950
有刺的猬
有刺的猬 2021-01-13 19:47

This is what I have so far. It works; outputing the folder path to temp to a text file. What I really want, is to output the data to a variable. Every example I see online

2条回答
  •  庸人自扰
    2021-01-13 20:27

    This may be done with the Windows Script Host Exec command. StdOut, StdIn, and StdErr may all be accessed, and ERRORLEVEL is available when the command completes.

    Dim strMessage, strScript, strStdErr, strStdOut
    Dim oExec, oWshShell, intErrorLevel
    Dim ComSpec
    
    Set oWshShell = CreateObject("WScript.Shell")
    ComSpec = oWshShell.ExpandEnvironmentStrings("%comspec%")
    
    intErrorLevel = 0
    strScript = ComSpec & " /C echo %temp%"
    
    On Error Resume Next
    Set oExec = oWshShell.Exec (strScript)
    If (Err.Number <> 0) Then
      strMessage = "Error: " & Err.Message
      intErrorLevel = 1
    Else
      Do While oExec.Status = 0
        Do While Not oExec.StdOut.AtEndOfStream
          strStdOut = strStdOut & oExec.StdOut.ReadLine & vbCrLf
        Loop
        Do While Not oExec.StdErr.AtEndOfStream
          strStdErr = strStdErr & oExec.StdErr.ReadLine & vbCrLf
        Loop
        WScript.Sleep 0
      Loop
      intErrorLevel = oExec.ExitCode
      strMessage = strStdOut & strStdErr & CStr(intErrorLevel)
    End If
    
    WScript.Echo (strMessage)
    

    NOTE: Replacing "ReadLine" above with "Read(1)" accomplishes the same thing, but adds an ability to process characters rather than whole lines.

提交回复
热议问题