【发布时间】:2019-05-08 16:22:37
【问题描述】:
我有大量的图像文件,时间跨度近 20 年,其中主题由目录名称标识,并且大多数照片本身都有一个通用名称,但其中一些具有更具体的名称。 我正在编写一个脚本,将目录名添加到特定目录中所有文件的文件名中。好吧,我至少在努力。 自从我使用 VBScript 以来已经有几年了,我似乎非常生疏。 我在语法格式方面面临挑战。
当我有 Option Explicit(在第 6 行)时,它会给出第 6 行的错误,字符 1,错误:预期的语句,代码:800A0400(在我的共享代码中,由于添加了文件开头行,所以它将是第 7 行)
如果我将其注释掉,我会在导入语句而不是第 3 行,字符 1,错误:类型不匹配:'Imports',代码:800A000D(在我的共享代码中,它将是第 4 行,因为添加的文件开头行)
我花了几个小时在谷歌上搜索可能的原因,但无济于事,因此我正在向社区寻求帮助以正确设置此脚本的格式。
任何关于完成此任务的更好脚本方法的 cmets 也将不胜感激。
我将放入文件的整个代码,因为我不知道它的哪一部分将是相关方面。
在代码中,目前设置为只为每个文件创建一个消息框作为测试措施,以确保变量具有我认为它们具有的值。 用于重命名文件的注释掉的代码是真正的预期目的。 但是,我坚持文件第一部分的正确格式。 一般来说,我从命令行执行此操作:cscript.exe c:\MyTools\addDir2FileName.vbs
我通过 Windows 资源管理器启动它以获取带有行号的更具体的错误代码。
我添加了文件开头和文件结尾 cmets 只是为了在这篇文章中清晰。
' ####### Beginning of File
' Renames all files in a directory prepending the directory name to the file name
Imports System
Imports System.IO
Option Explicit
Dim WshShell, strOldFull, strNewFull, strFullPath, strCurDir
Dim strCurrentName, strNewName, strMessage, dir, fileObj, fs, fo
' Get the current directory
Set WshShell = CreateObject("WScript.Shell")
strFullPath = WshShell.CurrentDirectory
'Get folder properties to get just the name without path
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set fo=fs.GetFolder(strFullPath)
strCurDir = fo.Name
'Iterate through the directory
set dir = DirectoryInfo(strFullPath)
For Each fileObj In dir.GetFiles()
strCurrentName = fileObj.Name
strNewName = strCurDir & " - " & strCurrentName
' For testing purposes to make sure everything is as expected
' Creates a message box for each file instead of actually renaming it
strMessage = "Old Name: " & strCurrentName & chr(13) & chr(10) & "New Name: " & strNewName
MsgBox strMessage
' Renaming the file
' strOldFull = fs.BuildPath(CurrentDirectory, strCurrentName)
' strNewFull = fs.BuildPath(CurrentDirectory, strNewName)
' My.Computer.FileSystem.RenameFile(strOldFull, strNewFull)
Next
WshShell = Nothing
fo = Nothing
fs = Nothing
' ### End of File
预期文件“C:\Pictures\Trip to Nice\DCM001.jpg”将重命名为“C:\Pictures\Trip to Nice\Trip to Nice - DCM001.jpg”,并且所有文件在运行脚本的目录将被类似地重命名。 好吧,更准确地说,当前格式化的输出将产生一个消息框,上面写着“旧名称:C:\Pictures\Trip to Nice\DCM001.jpg 新名称:C:\Pictures\Trip to Nice\Trip to Nice - DCM001.jpg”,并且将为目录中的所有文件生成一个消息框。是的,我只会在包含 3 个文件的测试目录中运行消息框版本。我不想得到 50,000 个消息框,哈哈。
由于 Import 语句或 Option Explicit 的格式问题,或者可能是我遗漏或有错误的其他语法片段,目前没有输出。
感谢您的宝贵时间以及任何人能够提供的任何帮助。这是我第一次向社区发帖,但我一直很欣赏所提供的答案。通常,我可以发现我的问题已经得到解答,但我被这个问题难住了......
【问题讨论】:
-
Imports语句不是有效的 VBScript 语法。 -
@Geert,我不认为这是该问题的重复,因为我的问题不是“导致此错误的原因”而是“我如何完成此任务”,而我不是这样非常关注这一单一方面,并对任何给定的解决方案持开放态度,正如我在您发表评论之前发布的解决方案中所表示的那样,该解决方案并未尝试利用 Imports 声明。
标签: file vbscript compiler-errors runtime-error option-explicit