程序员的知识教程库

网站首页 > 教程分享 正文

VBS实用小技巧--合并不同文件夹下的文件

henian88 2024-10-24 10:26:59 教程分享 5 ℃ 0 评论

在我们使用windows操作系统过程中,往往会遇到所需文件分属于不同文件下的情况。此时如果想对这些文件统一进行打包或者操作,则需要手工将其复制到一个文件夹下,非常没有效率。本文所叙述的内容是利用windows系统自带的脚本工具:VBS,仅需几行代码就可以搞定上述问题。

代码功能

假设在"E:\photo\"文件夹下有名称分别为“1,2,3”的三个文件夹。此时我们想要将1,2,3三个文件夹下的文件剪切至“E:\photo_bak\”路径下。

代码介绍

set fso=createobject("Scripting.FilesystemObject")
set folder=fso.getFolder("E:\photo\")
                         for each fder in folder.SubFolders
                         for each fl in fder.Filescall
                         fl.move("E:\photo_bak\")
                         next
                         next

如上所示即为实现功能的核心代码部分,非常简单。那么它是怎么工作的呢?

首先,我们创建一个“FileSystemObject”对象(这里对该对象不做过多解释,大家只要了解该对象是可以对windows文件系统进行操作的脚本库对象即可)。

之后,利用fso对象的getFolder方法获取源路径的文件夹对象。

接着,我们开始对路径下的文件夹及文件夹下的文件开始进行遍历,这里我们用到了文件夹对象的两个属性:SubFolders以及Files。这两个属性分别返回该文件夹对象的子文件夹对象集合以及文件集合。利用for each Object in Collection 语法对子文件夹集合以及每个子文件夹对象下的文件集合开始遍历,并最终取得我们要进行操作的文件对象 “fl”

最后,利用文件对象“fl”自带的move方法("move(String desPath)")将文件剪切至目标目录下。

注意事项

move方法参数一定为目录形式,即路径应以"\"符号结尾,如上述代码我们将“fl.move("E:\photo_bak\")”修改成“fl.move("E:\photo_bak")”,系统认为是要将fl对象剪切并替换E盘下的photo_bak文件造成报错。

功能扩展

上述功能我们是将源文件目录及目标目录直接写入到脚本中,程序的扩展性和健壮性都很差,如下脚本可从一定程度上克服这个问题:

dim inp
on error resume next
inp=InputBox("Please insert sourcepath")
set fso=createobject("Scripting.FileSystemObject")
if fso.FolderExists(inp) then
set folder_src=fso.getFolder(inp)
else
msgbox "The source path does not exists"
Wscript.quit()
end if
desp=inputbox("Please insert destinationpath")
if fso.FolderExists(desp) then
set folder_des=fso.getFolder(desp)
else
check=msgbox("The destination folder does not exist, Do you need to create?",vbYesNoCancel)
if check then
set folder_des=fso.createFolder(desp)
else
WScript.quit()
end if
end if
for each fder in folder_src.SubFolders
for each fl in fder.Files
call fl.move(desp)
next
next
if Err.Number<>0 then
  msgbox Err.Description
end if
dim inp
on error resume next
inp=InputBox("Please insert sourcepath")
set fso=createobject("Scripting.FileSystemObject")
if fso.FolderExists(inp) then
set folder_src=fso.getFolder(inp)
else
msgbox "The source path does not exists"
Wscript.quit()
end if
desp=inputbox("Please insert destinationpath")
if fso.FolderExists(desp) then
set folder_des=fso.getFolder(desp)
else
check=msgbox("The destination folder does not exist, Do you need to create?",vbYesNoCancel)
if check then
set folder_des=fso.createFolder(desp)
else
WScript.quit()
end if
end if
for each fder in folder_src.SubFolders
for each fl in fder.Files
call fl.move(desp)
next
next
if Err.Number<>0 then
  msgbox Err.Description
end if

如上脚本可以通过自己选定源目录及目标目录的形式来应对更为一般的情况,此时要注意输入目标目录时,仍需要以"\"符号作为结尾,否则会出现报错提示框"文件已存在"

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表