18

I am trying to rename a file and was using the below code but it does not seem to work. Can someone please tell me why? What is the correct way to rename a file from VBScript?

FSO.GetFile("MyFile.txt).Name = "Hello.txt"

I am using this thread for reference: Rename files without copying in same folder

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user505210
  • 1,362
  • 11
  • 28
  • 50

7 Answers7

40

You can rename the file using FSO by moving it: MoveFile Method.

Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "A.txt", "B.txt"
user692942
  • 16,398
  • 7
  • 76
  • 175
Roman R.
  • 68,205
  • 6
  • 94
  • 158
  • I don't want to move the file just rename it ..can u give an example of what ur saying. – user505210 Jul 15 '13 at 17:59
  • I tried using the MoveTo method by this code FSO.MoveTo \\net\stat\help.txt \\net\stat\main.css but it does not work – user505210 Jul 15 '13 at 18:12
  • 1
    Moving (`MoveFile`, not `MoveTo`) within the volume is not so much different from renaming, it is actually the same operation: update of the file descriptor without copying the actual data. This is basically the reason why you don't have a dedicate renaming method. – Roman R. Jul 15 '13 at 18:15
  • Sorry used MoveFile ..MoveTo was a typo ..Still does not work – user505210 Jul 15 '13 at 18:20
  • It does work, it is more likely that you are doing something wrong: syntax, names, permissions etc. – Roman R. Jul 15 '13 at 18:26
  • K just checked the code by inserting an Err clause and I am getting permission denied error..I am not sure why ..The script runs as administrator and I can create files and add stuff to it without any issues..checking now to see whats going on – user505210 Jul 15 '13 at 18:33
  • 2
    Got the issue..was writing to the file early in code and the object was not closed..Thanks for the help guys – user505210 Jul 15 '13 at 18:41
  • This fails if the target file already exists, see https://stackoverflow.com/a/9015037/1026 – Nickolay Jan 24 '19 at 13:13
  • @Nickolay: Well, renaming does not assume overwriting too – Roman R. Jan 24 '19 at 14:22
14

I see only one reason your code to not work, missed quote after file name string:

VBScript:

FSO.GetFile("MyFile.txt[missed_quote_here]).Name = "Hello.txt"
Evan
  • 600
  • 2
  • 7
  • 34
seeker
  • 318
  • 3
  • 11
1

Yes you can do that.
Here I am renaming a .exe file to .txt file

rename a file

Dim objFso  
Set objFso= CreateObject("Scripting.FileSystemObject")  
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"
Dilip
  • 2,622
  • 1
  • 20
  • 27
0
Rename filename by searching the last character of name. For example, 

Original Filename: TestFile.txt_001
Begin Character need to be removed: _
Result: TestFile.txt

Option Explicit

Dim oWSH
Dim vbsInterpreter
Dim arg1 'As String
Dim arg2 'As String
Dim newFilename 'As string

Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"

ForceConsole()

arg1 = WScript.Arguments(0)
arg2 = WScript.Arguments(1)

WScript.StdOut.WriteLine "This is a test script."
Dim result 
result = InstrRev(arg1, arg2, -1)
If result > 0 then
    newFilename = Mid(arg1, 1, result - 1)
    Dim Fso
    Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
    Fso.MoveFile arg1, newFilename
    WScript.StdOut.WriteLine newFilename
End If



Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) &     WScript.ScriptFullName & Chr(34)
        WScript.Quit
    End If
 End Function
Cavin
  • 11
  • 3
0

From what I understand, your context is to download from ALM. In this case, ALM saves the files under: C:/Users/user/AppData/Local/Temp/TD_80/ALM_VERSION/random_string/Attach/artefact_type/ID

where :

ALM_VERSION is the version of your alm installation, e.g 12.53.2.0_952

artefact_type is the type of the artefact, e.g : REQ

ID is the ID of the artefact

Herebelow a code sample which connects to an instance of ALM, domain 'DEFAUT', project 'MY_PROJECT', gets all the attachments from a REQ with id 6 and saves them in c:/tmp. It's ruby code, but it's easy to transcribe to VBSctript

require 'win32ole'
require 'fileutils'

# login to ALM and domain/project 
alm_server = ENV['CURRRENT_ALM_SERVER']
tdc = WIN32OLE.new('TDApiOle80.TDConnection')
tdc.InitConnectionEx(alm_server)
username, password = ENV['ALM_CREDENTIALS'].split(':')
tdc.Login(username, password)
tdc.Connect('DEFAULT', 'MY_PROJECT')

# get a handle for the Requirements 
reqFact = tdc.ReqFactory

# get Requirement with ID=6
req = reqFact.item(6)

# get a handle for the attachment of REQ 
att = req.Attachments

# get a handle for the list of attachements
attList = att.NewList("")

thePath= 'c:/tmp'

# for each attachment:
attList.each do |el|
  clientPath = nil

  # download the attachment to its default location
  el.Load true, clientPath

  baseName = File.basename(el.FileName)
  dirName = File.dirname(el.FileName)
  puts "file downloaded as : #{baseName}\n in Folder #{dirName}"  
  FileUtils.mkdir_p thePath
  puts "now moving #{baseName} to #{thePath}"  
  FileUtils.mv el.FileName, thePath
end

The output:

=> file downloaded as : REQ_6_20191112_143346.png

=> in Folder C:\Users\user\AppData\Local\Temp\TD_80\12.53.2.0_952\e68ab622\Attach\REQ\6

=> now moving REQ_6_20191112_143346.png to c:/tmp

kirkytullins
  • 143
  • 5
  • What makes you think this question is related to ALM? I'm not seeing any reference to ALM at all. I'm not saying it isn't a good answer, but I think it's for a different question. If you think this might be useful you can post your own question and answer it immediately yourself. – Geert Bellekens Dec 13 '19 at 08:32
  • This question was referenced from another question (https://stackoverflow.com/questions/59262400/is-it-possible-to-rename-the-downloaded-attachment-from-alm). But now, I realize that I posted in the wrong question, sorry about that – kirkytullins Dec 13 '19 at 12:46
-1

Below code absolutely worked for me to update File extension.

Ex: abc.pdf to abc.txt

Filepath = "Pls mention your Filepath"

Set objFso = CreateObject("Scripting.FileSystemObject")

'' Below line of code is to get the object for Folder where list of files are located 
Set objFolder = objFso.GetFolder(Filepath)

'' Below line of code used to get the collection object to hold list of files located in the Filepath.
Set FileCollection = objFolder.Files

For Each file In FileCollection

    WScript.Echo "File name ->" + file.Name
    ''Instr used to Return the position of the first occurrence of "." within the File name
    s = InStr(1, file.Name, ".",1)
    WScript.Echo s
    WScript.Echo "Extn --> " + Mid(file.Name, s, Len(file.Name))

    'Left(file.Name,s-1) = Used to fetch the file name without extension
    ' Move method is used to move the file in the Desitnation folder you mentioned
    file.Move(Filepath & Left(file.Name,s-1)&".txt") 

Next
Greenonline
  • 1,330
  • 8
  • 23
  • 31
  • 1
    You shouldn't use string operations to get the extension of a file. You can use `FileSystemObject.GetExtensionName()` to get the extension. – Geert Bellekens Dec 21 '18 at 07:07
-1

Rename File using VB SCript.

  1. Create Folder Source and Archive in D : Drive. [You can choose other drive but make change in code from D:\Source to C:\Source in case you create folder in C: Drive]
  2. Save files in Source folder to be renamed.
  3. Save below code and save it as .vbs e.g ChangeFileName.vbs
  4. Run file and the file will be renamed with existing file name and current date
 Option Explicit 
    
    Dim fso,sfolder,fs,f1,CFileName,strRename,NewFilename,GFileName,CFolderName,CFolderName1,Dfolder,afolder
    
    Dim myDate
    
    myDate =Date
    
    Function pd(n, totalDigits) 
    
            if totalDigits > len(n) then 
    
                pd = String(totalDigits-len(n),"0") & n 
    
            else 
    
                pd = n 
    
            end if 
    
    End Function 
    
    myDate=
    Pd(DAY(date()),2) & _ 
           
    Pd(Month(date()),2) & _ 
           
    YEAR(Date()) 
    
           
    'MsgBox ("Create Folders  'Source' 'Destination ' and  'Archive' in D drive.  Save PDF files into Source Folder ")
           
    sfolder="D:\Source\"
    
    'Dfolder="D:\Destination\"
    
    afolder="D:\archive\"
    
    Set fso= CreateObject("Scripting.FileSystemObject")
    
    Set fs= fso.GetFolder(sfolder)
    
    For each f1 in fs.files
    
                CFileName=sfolder & f1.name
    
                CFolderName1=f1.name
    
                CFolderName=Replace(CFolderName1,"." & fso.GetExtensionName(f1.Path),"")
    
                'Msgbox CFileName 
    
                'MsgBox CFolderName 
    
                'MsgBox myDate
    
                GFileName=fso.GetFileName(sfolder)
    
                'strRename="DA009B_"& CFolderName &"_20032019"
    
                strRename= "DA009B_"& CFolderName &"_"& myDate &""
    
                NewFilename=replace(CFileName,CFolderName,strRename)
    
                'fso.CopyFile CFolderName1 , afolder
    
                fso.MoveFile CFileName , NewFilename
    
                'fso.CopyFile CFolderName, Dfolder
    
                
    Next
    
    MsgBox "File Renamed Successfully !!! "
    
    Set fso= Nothing
    
    Set fs=Nothing
Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Suraj Rao Mar 26 '19 at 09:48
  • You messed up the code formatting (after someone had already fixed that for you). Please edit and rectify. – Geert Bellekens Mar 26 '19 at 10:08