How do I rename a file using VBScript?

后端 未结 7 1929
北恋
北恋 2020-12-11 01:44

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 VBScrip

相关标签:
7条回答
  • 2020-12-11 02:16
    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
    
    0 讨论(0)
  • 2020-12-11 02:26

    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"
    
    0 讨论(0)
  • 2020-12-11 02:28

    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

    0 讨论(0)
  • 2020-12-11 02:28

    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

    0 讨论(0)
  • 2020-12-11 02:29

    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
    
    0 讨论(0)
  • 2020-12-11 02:30

    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"
    
    0 讨论(0)
提交回复
热议问题