首页 > 解决方案 > 在未找到 BGInfo 文件中使用 VBScript 时出错

问题描述

我是一个业余的 VB 脚本编写者。

我正在创建一个脚本来输出 ID。该文件包含“ad.annnet.id = 564654068”行。需要输出“ID:564654068”

With New RegExp
    .Pattern = "\nID=(\d+)"
    Echo .Execute(CreateObject("Scripting.FileSystemObject").OpenTextFile("this.conf").ReadAll)(0).Submatches(0)
End With

标签: regexvbscript

解决方案


脚本存在多个问题,“找不到文件”错误的实际原因是@craig在他们的回答中指出FileSystemObject找不到文件“this.conf”。这是因为该OpenTextFile()方法不支持相对路径,并且需要文件的绝对路径,无论它是否与正在执行的脚本位于同一目录中。

您可以通过调用GetAbsolutePathName()并传入文件名来解决此问题。

来自官方文档 - GetAbsolutePathName 方法


假设当前目录是 c:\mydocuments\reports,下表说明了该GetAbsolutePathName方法的行为。

路径规范 (JScript) 路径规范 (VBScript) 返回路径
“C:” “C:” “c:\我的文档\报告”
“C:..” “C:..” “c:\我的文档”
“C:\” “C:” “C:”
“c: . \may97” “c: . \may97” "c:\mydocuments\reports*.*\may97"
“区域 1” “区域 1” "c:\mydocuments\reports\region1"
"c:\..\..\mydocuments" “c:....\我的文档” “c:\我的文档”

像这样的东西应该有效;

'Read the file from the current directory (can be different from the directory executing the script, check the execution).
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim filename: filename = "this.conf"
Dim filepath: filepath = fso.GetAbsolutePathName(filename)
Dim filecontent: filecontent = fso.OpenTextFile(filepath).ReadAll

更新:看来您毕竟可以使用路径修饰符OpenTextFile()(谢谢@LesFerch),所以这也应该有效;

'Read the file from the current directory (can be different from the directory executing the script, check the execution).
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim filename: filename = ".\this.conf" '.\ denotes the current directory
Dim filecontent: filecontent = fso.OpenTextFile(filename).ReadAll

另一个问题是当前RegExp模式与您的期望不匹配,建议您先使用正则表达式 101之类的东西来测试您的正则表达式。


推荐阅读