【问题标题】:How can I redirect my vbscript output to a file using batch file?如何使用批处理文件将我的 vbscript 输出重定向到文件?
【发布时间】:2020-11-18 10:54:45
【问题描述】:

我是 Windows 脚本的新手。我有一个使用 WinRAR CLI 实用程序进行归档的简单脚本。我必须使用批处理文件来安排这个脚本。在归档过程中会出现一些错误,我希望它们写在一个简单的文本文件中,或者至少我可以将归档的整个输出写在一个文件中。如何更改我的代码来执行此操作?

Dim MyDate
Dim OutputFile 
const WaitUntilFinished = true, DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0 

MyDate = Replace(Date, "/", "-")
OutputFile = "backup-" & mydate & ".rar" 

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.CurrentDirectory = "C:\Users\ABC\Desktop\"
objShell.Run "C:\windows\Rar.exe a .\VBScripts\backups\" & OutputFile & " software", ShowWindow, WaitUntilFinished

objShell.Popup "Archiving Completed Successfully!",5, "Scheduled Backup"
Set objShell = Nothing

批处理文件是这样的;

@echo off 
start /wait C:\Users\ABC\Desktop\VBScripts\scheduled_backup.vbs 

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    更改您的命令行以包括重定向到日志文件:

    logfile = "C:\path\to\your.log"
    objShell.Run "%COMSPEC% /c C:\windows\Rar.exe a .\VBScripts\backups\" & _
      OutputFile & " software >""" & logfile & """", ShowWindow, WaitUntilFinished
    

    【讨论】:

    • 谢谢。这就是我一直在寻找的。它适用于我的两种情况。
    【解决方案2】:

    使用this函数代替WScript.Shell.Run:

    ' Runs an external program and pipes it's output to
    ' the StdOut and StdErr streams of the current script.
    ' Returns the exit code of the external program.
    Function Run (ByVal cmd)
       Dim sh: Set sh = CreateObject("WScript.Shell")
       Dim wsx: Set wsx = Sh.Exec(cmd)
       If wsx.ProcessID = 0 And wsx.Status = 1 Then
          ' (The Win98 version of VBScript does not detect WshShell.Exec errors)
          Err.Raise vbObjectError,,"WshShell.Exec failed."
       End If
       Do
          Dim Status: Status = wsx.Status
          WScript.StdOut.Write wsx.StdOut.ReadAll()
          WScript.StdErr.Write wsx.StdErr.ReadAll()
          If Status <> 0 Then Exit Do
          WScript.Sleep 10
       Loop
       Run = wsx.ExitCode
    End Function
    

    在您的批处理中调用 script 而不是 start 并使用重定向:

    script //nologo C:\Users\ABC\Desktop\VBScripts\scheduled_backup.vbs 2> errors.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多