1

I want to replace a file named with different name using VBScript. The input file name may or may not contain blank spaces.

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"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Possibly related: [Issue with MoveFile method to overwrite file in Destination in vbscript?](//stackoverflow.com/a/17065729) – user692942 Mar 21 '17 at 13:46
  • Possibly related: [Copy a file from one folder to another using vbscripting](//stackoverflow.com/q/1260740) – user692942 Mar 21 '17 at 13:49

1 Answers1

2

Perhaps surprisingly, CopyFile creates a copy of the source file. To rename a file you could use MoveFile, but the usual approach is to simply change the name of the file:

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

Edit: If you actually mean to replace one file with another file, you can do so with CopyFile by setting the third parameter (overwrite) to True, as @Lankymart pointed out in the comments.

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

If you don't want to keep the source file you need to delete it after the copy operation (VBScript doesn't allow moving a file over an existing file). Alternatively you can delete the destination file first and then move or rename the source file.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 1
    Do they want to keep the original though and overwrite still if the destination file exists? if so just specifying `objFSO.CopyFile "D:\Development\abc def.txt", "D:\Development\xyz.txt", True` would be enough. The fact the question says *"Replace"* would suggest not, but I wouldn't assume either. – user692942 Mar 21 '17 at 13:44