当前位置: 移动技术网 > IT编程>脚本编程>VBScript > 使用脚本自动压缩指定目标下的所有文件的代码

使用脚本自动压缩指定目标下的所有文件的代码

2017年12月08日  | 移动技术网IT编程  | 我要评论

2011年新婚姻法,斯柯达广域网,诺基亚8888

为了解决这类问题,我使用visual basic scripting设计了一个脚本,可以自动达到这个目标。在本脚本中,自动压缩所有文件。为了避免将脚本自己也压缩进去,使用了一些判断。
复制代码 代码如下:

call main()
sub main()
dim fs '文件系统。
dim f 'folder
dim fc 'files
dim s 'string
dim ws 'shell。
dim subfs
dim fi
'创建shell。
set ws = createobject("wscript.shell")
'创建文件对象。
set fs = createobject("scripting.filesystemobject")
set f = fs.getfolder(ws.currentdirectory)
handle_files(ws.currentdirectory)
set subfs = f.subfolders
'遍历每个子目录。
for each fi in subfs
call listsub(fi.path)
next
end sub
sub listsub(filename)
on error resume next
dim subfs '子目录。
'首先处理当前目录。
handle_files(filename)
'创建文件对象。
set fs = createobject("scripting.filesystemobject")
set f = fs.getfolder(filename)
set subfs = f.subfolders
for each fi in subfs
call listsub(fi.path)
next
end sub
'处理每个目录下的文件。
sub handle_files(foldername)
'创建文件对象。
set fs = createobject("scripting.filesystemobject")
set f = fs.getfolder(foldername)
set fc = f.files
'创建shell。
set ws = createobject("wscript.shell")
'遍历文件对象。
for each fl in fc
if ((instr(fl.name,"vbs") = 0) and (instr(fl.name,"rar") = 0)) then
'进行压缩。
s = "winrar m -ep " & fl.path & ".rar " & fl.path
ws.run s, 0, true
end if
next
end sub
sub output(string)
wscript.echo string
end sub

一种更加巧妙的方法
对上个脚本稍加改动,使用正则表达式(regular expression ),可以方便我们的判断过程。修改后的脚本程序如下所示。注意我们这里排除的是不压缩的文件类型。
复制代码 代码如下:

call main()
sub main()
dim fs '文件系统。
dim f 'folder
dim fc 'files
dim s 'string
dim ws 'shell。
dim subfs
dim fi
'创建shell。
set ws = createobject("wscript.shell")
'创建文件对象。
set fs = createobject("scripting.filesystemobject")
set f = fs.getfolder(ws.currentdirectory)
handle_files(ws.currentdirectory)
set subfs = f.subfolders
'遍历每个子目录。
for each fi in subfs
call listsub(fi.path)
next
end sub
sub listsub(filename)
on error resume next
dim subfs '子目录。
'首先处理当前目录。
handle_files(filename)
'创建文件对象。
set fs = createobject("scripting.filesystemobject")
set f = fs.getfolder(filename)
set subfs = f.subfolders
for each fi in subfs
call listsub(fi.path)
next
end sub
'处理每个目录下的文件。
sub handle_files(foldername)
'创建文件对象。
set fs = createobject("scripting.filesystemobject")
set f = fs.getfolder(foldername)
set fc = f.files
'创建shell。
set ws = createobject("wscript.shell")
'遍历文件对象。
for each fl in fc
if ( regexptest(".vbs|.rar|.zip",fl.name) = false) then
'进行压缩。
s = "winrar m -ep " & fl.path & ".rar " & fl.path
output s
ws.run s, 0, true
end if
next
end sub
sub output(string)
wscript.echo string
end sub
'使用正则表达式进行判断。
function regexptest(patrn, strng)
dim regex, retval ' create variable.
set regex = new regexp ' create regular expression.
regex.pattern = patrn ' set pattern.
regex.ignorecase = false ' set case sensitivity.
retval = regex.test(strng) ' execute the search test.
if retval then
regexptest = true
else
regexptest = false
end if
end function

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网