简体   繁体   English

如何使用 VBScript 重命名文件?

[英]How do I rename a file using VBScript?

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?从 VBScript 重命名文件的正确方法是什么?

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

I am using this thread for reference: Rename files without copying in same folder我正在使用此线程作为参考: 重命名文件而不在同一文件夹中复制

You can rename the file using FSO by moving it: MoveFile Method .您可以通过移动文件使用 FSO 重命名文件: MoveFile Method

Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "A.txt", "B.txt"

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"

Yes you can do that.是的,你可以这样做。
Here I am renaming a .exe file to .txt file在这里,我将 .exe 文件重命名为 .txt 文件

rename a file重命名文件

Dim objFso  
Set objFso= CreateObject("Scripting.FileSystemObject")  
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"
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

From what I understand, your context is to download from ALM.据我了解,您的上下文是从 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在这种情况下,ALM 将文件保存在: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, eg 12.53.2.0_952 ALM_VERSION是你的 alm 安装版本,例如 12.53.2.0_952

artefact_type is the type of the artefact, eg : REQ artefact_type人工制品的类型,例如:REQ

ID is the ID of the artefact ID是人工制品的ID

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.下面是连接到 ALM 实例、域“DEFAUT”、项目“MY_PROJECT”的代码示例,从 ID 为 6 的 REQ 中获取所有附件并将它们保存在 c:/tmp 中。 It's ruby code, but it's easy to transcribe to VBSctript这是 ruby​​ 代码,但很容易转录为 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 => 文件下载为:REQ_6_20191112_143346.png

=> in Folder C:\\Users\\user\\AppData\\Local\\Temp\\TD_80\\12.53.2.0_952\\e68ab622\\Attach\\REQ\\6 => 在文件夹 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 => 现在将 REQ_6_20191112_143346.png 移动到 c:/tmp

Below code absolutely worked for me to update File extension.下面的代码绝对适合我更新文件扩展名。

Ex: abc.pdf to abc.txt例如:abc.pdf 到 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

Rename File using VB SCript.使用 VB 脚本重命名文件。

  1. Create Folder Source and Archive in D : Drive.在 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] [您可以选择其他驱动器,但如果您在 C: 驱动器中创建文件夹,请将代码从 D:\\Source 更改为 C:\\Source]
  2. Save files in Source folder to be renamed.将文件保存在要重命名的源文件夹中。
  3. Save below code and save it as .vbs eg ChangeFileName.vbs保存以下代码并将其另存为 .vbs 例如 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 fso,sfolder,fs,f1,CFileName,strRename,NewFilename,GFileName,CFolderName,CFolderName1,Dfolder,afolder

    Dim myDate调暗日期

    myDate =Date我的日期 = 日期

    Function pd(n, totalDigits)函数 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) & _ myDate= Pd(DAY(date()),2) & _

    Pd(Month(date()),2) & _ Pd(Month(date()),2) & _

    YEAR(Date())年(日期())

    'MsgBox ("Create Folders 'Source' 'Destination ' and 'Archive' in D drive. Save PDF files into Source Folder ") 'MsgBox ("在 D 盘中创建文件夹 'Source' 'Destination' 和 'Archive'。将 PDF 文件保存到源文件夹中")

    sfolder="D:\\Source\\" sfolder="D:\\源\\"

    'Dfolder="D:\\Destination\\" 'Dfolder="D:\\目的地\\"

    afolder="D:\\archive\\" afolder="D:\\存档\\"

    Set fso= CreateObject("Scripting.FileSystemObject") Set fso= CreateObject("Scripting.FileSystemObject")

    Set fs= fso.GetFolder(sfolder)设置 fs= fso.GetFolder(sfolder)

    For each f1 in fs.files对于 fs.files 中的每个 f1

     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 !!! " MsgBox "文件重命名成功!!!"

    Set fso= Nothing设置 fso=Nothing

    Set fs=Nothing设置 fs=Nothing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM