VBScript 继续循环重命名文件

VBScript Continues Loop to Rename File

尝试创建一个连续循环的 VBScript,直到它找到特定文件并将其重命名为不同的扩展名,分分秒秒:

do
Set fso = CreateObject("Scripting.FileSystemObject")
Set myFile = fso.GetFile("C:\Users\user\Downloads\test.txt")

If (fso.FileExists(myFile)) Then
     myFile.Move "C:\Users\user\Downloads\test.xml"
End If

WScript.Sleep 1000

loop

上面的方法有效并重命名了文件,但是在循环时它会出错 "file cannot be found"。将需要添加一个 else 语句,但很难做到这一点。

在尝试实例化 File 对象引用之前先尝试检查文件是否存在。

Dim fso, myFile, source, dest

Set fso = CreateObject("Scripting.FileSystemObject")

Do
  source = "C:\Users\user\Downloads\test.txt"
  dest = "C:\Users\user\Downloads\test.xml"

  If fso.FileExists(source) Then
    Set myFile = fso.GetFile(source)
    Call myFile.Move(dest)
    Set myFile = Nothing
  End If
  WScript.Sleep 1000
Loop

Set fso = Nothing

* 这是一个基于原始例子的伪代码例子

fso 实例化移到循环之外以避免在每次迭代时重新实例化它。

目前不确定循环的目的是什么,但如果你打算 运行 这很长一段时间,最好通过将它们设置为 [= 来取消实例化任何引用以帮助优化脚本内存13=].

Would also recommend while testing the loop to limit the iterations using a counter and exiting the loop if the count is exceeded.