【问题标题】:VBscript output not writing correctlyVBscript 输出未正确写入
【发布时间】:2012-10-14 01:35:47
【问题描述】:

脚本专家您好,

我在远程服务器上有一个日志文件.. 在远程服务器中c:\vb\text.log

我已将我的远程系统包含在list.Txt

server1
server2

以下是日志的示例..

application working
[10/23/2012 working

[10/24/2012 nos appdown
error found you need to check this

下面是我的脚本。

Set Fso = CreateObject("Scripting.FileSystemObject")
Set InFile = fso.OpenTextFile("list.Txt")
Set out = fso.CreateTextFile("error.log")

Const ForReading = 1
Do While Not (InFile.atEndOfStream)
  strComputer = InFile.ReadLine
  today = Date()
  Set fso = CreateObject("Scripting.FileSystemObject")
  strFilePath = "\\" & strComputer & "\c$\vb\"

  Set InputFile = fso.OpenTextFile(strFilePath & "text.log", 1)
  Do While Not (InputFile.AtEndOfStream)
    strLine = InputFile.ReadLine

    If Left(line, Len(today)+1) = "[" & today Then
      ' line timestamped with today's date
      If InStr(line, "nos") > 0 Then
        ' line contains "error"
        out.WriteLine InStr & vbTab & strComputer
      End If
    End If
  Loop
  InputFile.close
Loop

out.Close
InFile.Close

基本上,上述脚本应仅从text.log 文件(即[10/24/2012 nos appdown)中搜索当前日期行。然后如果在当前日期行中发现为“Nos”.. 那么它应该使用计算机名称写入error.log

在我的情况下,输出没有出现,但看起来它正在搜索字符串“Nos”。

请让我摆脱这种情况......

【问题讨论】:

标签: scripting vbscript


【解决方案1】:

错误在于您没有指定显式选项。像这样,

option explicit

这将迫使 VBScript 抱怨未声明的变量。通过这样做,您可以轻松地发现拼写错误的变量名。带dim语句的Delcare变量,像这样

dim Fso, out

再次运行脚本,对比发现您使用的是不存在且未初始化的变量:

strLine = InputFile.ReadLine ' Read stuff to strLine
If Left(line, Len(today)+1) = "[" & today Then ' ERROR. line has no value!

【讨论】:

    【解决方案2】:

    您对我的脚本的改编存在几个问题:

    • 正如vonPryz 已经指出的那样,这是问题的原因:

      strLine = InputFile.ReadLine
      If Left(line, Len(today)+1) = "[" & today Then

      当您将变量名从 file 更改为 strFile 时,您必须更改每个该变量的出现,而不仅仅是分配它的行。

    • out.WriteLine InStr & vbTab & strComputer

      这一行也会失败,因为InStr 是一个函数,而您没有使用正确数量的参数调用它。

    • today = Date()

      这不应该在循环中,除非您希望在脚本运行期间更改日期并且需要在每个循环周期中都有当前日期。

    • Set fso = CreateObject("Scripting.FileSystemObject")

      fso 在脚本开头被实例化。无需重新实例化它,尤其是在每个循环周期中。这只是浪费资源。

    • Const ForReading = 1

      当你从不使用常量时,定义它是没有意义的。

    • Do While Not ...

      使用Do Until ... 会更容易阅读和理解。

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      相关资源
      最近更新 更多