替换文件名中可能包含或不包含 space 的文本文件

Replace a text file which may or may not contain a space in file name

我想使用 VBScript 替换以不同名称命名的文件。输入的文件名可能包含也可能不包含空格。

Set objFSO = CreateObject("Scripting.FileSystemObject")
' First parameter: original location\file
' Second parameter: new location\file
objFSO.CopyFile "D:\Development\abc  def.txt", "D:\Development\xyz.txt"

也许令人惊讶的是,CopyFile 创建了源文件的副本。要重命名文件,您可以使用文件的 MoveFile, but the usual approach is to simply change the name

Set fso = CreateObject("Scripting.FileSystemobject")
fso.GetFile("D:\Development\abc  def.txt").Name = "xyz.txt"

编辑:如果你真的想用另一个文件替换一个文件,你可以在评论中指出CopyFile by setting the third parameter (overwrite) to True, as

fso.CopyFile "D:\Development\abc  def.txt", "D:\Development\xyz.txt", True

如果您不想保留源文件,则需要在复制操作后将其删除(VBScript 不允许将文件移动到现有文件之上)。或者,您可以先删除目标文件,然后移动或重命名源文件。