Windows脚本编程核心技术精解Chapter07.pdf

上传人:qwe****56 文档编号:70019740 上传时间:2023-01-14 格式:PDF 页数:30 大小:293.50KB
返回 下载 相关 举报
Windows脚本编程核心技术精解Chapter07.pdf_第1页
第1页 / 共30页
Windows脚本编程核心技术精解Chapter07.pdf_第2页
第2页 / 共30页
点击查看更多>>
资源描述

《Windows脚本编程核心技术精解Chapter07.pdf》由会员分享,可在线阅读,更多相关《Windows脚本编程核心技术精解Chapter07.pdf(30页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Chapter 7Accessing the File SystemIn This Chapter?Access drives,folders,and individual files?Peek into any file,and changing file contents at will?Determine free space on drives,and overcome the 2GB bug?Search the entire hard drive for outdated files or empty folders recursivelyThe Windows Scripting

2、 Host comes with a secret script extension,calledScripting.FileSystemObject.This object grants full access to theentire file system.In this chapter,youll discover how to peek into files,copy,move,delete and create new files from scratch.In addition,Ill show yousome workarounds to correctly deal with

3、 drive sizes greater than 2GBFinding the Secret Backdoor to the File SystemThe file system is one of the most interesting areas of your computer.Itswhere all of your data is stored,and there are numerous tasks that scriptscan handle for you,including reorganizing data,finding orphan files,doingbacku

4、ps,and more.How do you get access to your files?Both the WSH and VBScript lack filesystem commands.Theres no way to open files,delete data,or copy folders.However,this makes perfect sense because both WSH and VBScript aredesigned as platform-independent technologies.The file system,in contrast,is ve

5、ry special,and its technology can vary from operating system tooperating system.Still,your scripts have full access to your file system.Microsoft has placed allthe necessary commands into a separate module.scrrun.dllis automaticallyregistered as a Scripting.FileSystemObject COMcomponent,and whenever

6、you need file system support,just include a reference to this object in yourscripts.4684-8 ch07.f.qc 3/3/00 9:34 AM Page 219Accessing a driveWheres the secret back door to your file system?Actually,there are manydoors.One is to get access to any one of your drives using GetDrive:7-1.VBS get access t

7、o file system commands:set fs=CreateObject(“Scripting.FileSystemObject”)set drivec=fs.GetDrive(“C:”)MsgBox TypeName(drivec)emptyspace=drivec.AvailableSpaceMsgBox“Avaialable on C:“&_FormatNumber(emptyspace/10242,1)&“MB”This simple script accesses drive C:and returns a Driveobject.The Driveobject cont

8、ains many useful properties and methods.The AvailableSpaceproperty,for example,reports the available space on this drive(see Figure 7-1).Figure 7-1:Accessing a drive and retrieving Volume information.Actually,there are two very similar properties:AvailableSpaceandFreeSpace.Whereas FreeSpacereports t

9、he physically unoccupied space on the particular drive,AvailableSpacereports the space available to a user.It takes into account other limitations,such as disk quotas.Bothcommands report a maximum of 2GB of space.This is an intrinsic limitation,and you will hear more about it a little later in the c

10、hapter.You will alsodiscover methods to solve this limitation and report available space even on drives larger than 2GB.It only takes a couple of additional lines to enumerate all files in the rootfolder of your drive:7-2.VBS get access to file system commands:set fs=CreateObject(“Scripting.FileSyst

11、emObject”)set drivec=fs.GetDrive(“C:”)set root=drivec.RootFolderfor each file in root.fileslist=list&file.name&vbCrnextMsgBox list220Part II:Conquering the File SystemII4684-8 ch07.f.qc 3/3/00 9:34 AM Page 220When dealing with the file system,you work with many different objects.Inthe example,the dr

12、ive,the folder,and each individual file are represented byan individual object.Always remember to use Setwhenever you retrieve anobject reference and want to assign it to a variable.Finding information about properties andmethodsHow did I know about all the methods and properties I used in the previ

13、ousexamples?I didnt.I looked them up,and you can,too.In fact,its a good ideato first get together all the documentation you need to fully exploit theFileSystemObject.Its easyyouve already prepared the necessary toolsin the previous chapters.Have a look at Table 7-1:Table 7-1Scripts You Can Use To Au

14、to-Document COM ObjectsScriptDescription3-12.VBSFind out the particular syntax of a command.For example,enterGetDrive.3-7.VBSAuto-document all properties and methods of FileSystemObject:Enter the name of the object:scrrun.dll.Then enter the object youwant to document:FileSystemObject.3-10.VBSAuto-do

15、cument the Driveobject or any other object:Just enter thename of the object:for example,Drive5-12.VBSGenerate a fully color-coded reference to all the commands and objects.Enter the name of the COM object you want to document:scrrun.dll.Then open your documentation folder C:documentationscrrun andbr

16、owse through the automatically generated documentation files.OpenDrive.htm to discover the internal structure of the Driveobject you just used.Getting Details About Your DrivesAll your drives are represented by the Driveobject.How do you get one?You ask for it!One way is the GetDrivemethod,but there

17、 are others,too.The drives method enumerates all drives available on your system:7-3.VBS get access to file system commands:set fs=CreateObject(“Scripting.FileSystemObject”)retrieve list of all available drives:set drivecollection=fs.DrivesChapter 7:Accessing the File System221II4684-8 ch07.f.qc 3/3

18、/00 9:34 AM Page 221 enumerate drivesfor each drive in drivecollectionlist=list&drive.path&vbCrnextMsgBox listAnother“door”to the Driveobject goes the opposite direction:Get a folderobject and retrieve the Driveobject of the drive the folder is stored in:7-4.VBS get access to file system commands:se

19、t fs=CreateObject(“Scripting.FileSystemObject”)get access to a folder get windows folderset winfolder=fs.GetSpecialFolder(0)MsgBox“Windows folder:“&winfolder.name get drive object:set drive=winfolder.DriveMsgBox“Windows is installed on Drive“&drive.DriveLetterClosely examining the Drive objectThere

20、are many ways to retrieve a Driveobject.What can you do once youhave a reference to a Driveobject,though?Take a look at its internal structure(see Table 7-2):Table 7-2The Drive ObjectProperty/MethodDescriptionProperty AvailableSpaceGet available spaceProperty DriveLetter As StringDrive letterPropert

21、y DriveType As DriveTypeConstDrive typeProperty FileSystem As StringFilesystem typeProperty FreeSpaceGet drive free spaceProperty IsReady As BooleanCheck if disk is availableProperty Path As StringPathProperty RootFolder As IFolderRoot folderProperty SerialNumber As LongSerial numberProperty ShareNa

22、me As StringShare nameProperty TotalSizeGet total drive sizeProperty VolumeName As StringName of volume222Part II:Conquering the File SystemII4684-8 ch07.f.qc 3/3/00 9:34 AM Page 222Is the drive ready for action?Its always a good idea to prevent errors whenever possible(see Figure 7-2).Drives can ha

23、ve removable media such as a ZIP drive or disk drive.UseisReadyto find out whether a media is inserted before you start querying for any additional information:7-5.VBSset fs=CreateObject(“Scripting.FileSystemObject”)lets check drive A:set drivea=fs.GetDrive(“A:”)loop until drive is ready or user can

24、cels:do until drivea.isReadyresponse=MsgBox(“Please insert disk in drive A:!”,vbOKCancel)if response=vbCancel then user wants to quit,maybe no disk at hand:MsgBox“Cancel accepted”,vbExclamationWScript.Quitend ifloop lets label the drive:volname=drivea.VolumeNamenewname=InputBox(“Assign a new Volume

25、label to the disk:”,_,volname)if newname=vbEmpty then user cancelled:MsgBox“Volume name remains unchanged.”elsedrivea.VolumeName=newnameMsgBox“New Volume name assigned:“&newnameend ifFigure 7-2:Script checks whether a disk is inserted.isReadynot only prevents access to drives with no media inserted.

26、You can also,for example,write a shutdown script that closes Windows and uses isReadyto make sure no media is left in the drives.With the help of theCD-ROM tray API commands in Chapter 4,you can even automatically openCD ROM trays if media is left in the drive before shutting down the computer.All t

27、he methods and properties you discover throughout this book are justbuilding blocks,and the beauty of scripting is your freedom to use thesebuilding blocks in any way you want.Chapter 7:Accessing the File System223II4684-8 ch07.f.qc 3/3/00 9:34 AM Page 223Changing a drives volume nameVolumeNameis a

28、read/write property:You can both read the current volumelabel and assign new names.This is possible for all write-enabled drives,andyou even get to see your new label for hard drives in the Explorer window.The Volume label traditionally plays an important role with installation disks.By assigning vo

29、lume labels to disks,your script can check whether the userinserted the correct disk.Using a drives serial numberAnother important means of identification is the serial number.Each drivehas an individual serial number,and you can ask for it by querying theSerialNumberproperty.The serial number is as

30、signed during media formatting.Because the serialnumber will also be copied whenever you duplicate disks,its no good forcopy protection schemes.However,a serial number of 0 indicates that themedia wasnt fully formatted.“Pre-formatted”disks,for example,display aserial number of 0.Because its dangerou

31、s to store valuable data on suchdisks without fully formatting them beforehand,you can use the SerialNumber property to build additional security into your scripts.See thefollowing example.7-6.VBSset fs=CreateObject(“Scripting.FileSystemObject”)set drivea=fs.GetDrive(“A:”)loop until drive is ready o

32、r user cancels:do until drivea.isReadyresponse=MsgBox(“Please insert disk in drive A:!”,vbOKCancel)if response=vbCancel then user wants to quit,maybe no disk at hand:MsgBox“Cancel accepted”,vbExclamationWScript.Quitend ifloopserno=drivea.SerialNumberif serno=0 thenMsgBox“This disk was never fully fo

33、rmatted!”elseMsgBox“Disk serial number:“&sernoend ifDetermining drive type and file systemThere are many different drive types out there,and maybe you need to sort out read-only drives.How can you determine whether a drive is aCD-ROM drive?224Part II:Conquering the File SystemII4684-8 ch07.f.qc 3/3/

34、00 9:34 AM Page 224Easy.DriveTypetells you the type of drive,and FileSystemreports thetype of file system used on this drive(see Figure 7-3).Figure 7-3:Retrieve Volume Label and file system information.7-7.VBSset fs=CreateObject(“Scripting.FileSystemObject”)define array with clear text descriptiondt

35、=Split(“unknown;removable;fixed;remote;CD-ROM;RAM-Drive”,“;”)get list of drivesset drivecoll=fs.Drives enumerate all drivesfor each drive in drivecoll check whether drive is ready:if drive.isReady thendrivetype=drive.DriveTypefilesystem=drive.FileSystemlabel=drive.VolumeNameletter=drive.DriveLetterm

36、sg=msg&“Drive“&letter&“:(“&label _&“)“&dt(drivetype)&“(“&filesystem&“)”&vbCrelsemsg=msg&“Drive“&letter&“:is not ready.”&vbCrend ifnextMsgBox msg,vbInformationFinding out available space on drivesData storage is always a scarce resource.Your scripts will need to checkwhether there is enough storage s

37、pace available before starting a lengthycopy operation,and its a good idea to let scripts warn you once availablespace drops below a certain threshold.Chapter 7:Accessing the File System225II4684-8 ch07.f.qc 3/3/00 9:34 AM Page 225The Driveobject offers three properties,including AvailableSpace,Free

38、Space,and TotalSize.However,all three properties impose a seriouslimitation:They can only deal with drives up to a maximum size of 2GB.Or,inother words:Neither one will ever report more than 2GB.The FileSystemObjectuses old API functions to retrieve drive sizes.Theseold functions cant deal with driv

39、e sizes above 2GB.7-8.VBSset fs=CreateObject(“Scripting.FileSystemObject”)set drive=fs.GetDrive(“C:”)avail=drive.AvailableSpacefree=drive.FreeSpacetotal=drive.TotalSizemsg=“Statistics Drive C:”&vbCrmsg=msg&“Available Space:“&fn(avail)&vbCrmsg=msg&“Free Space:“&fn(free)&vbCrmsg=msg&“Total Size:“&fn(t

40、otal)MsgBox msgfunction fn(bytes)fn=FormatNumber(bytes/10242,2)&“MB”end functionAvailableSpaceand FreeSpacewill only differ if you have set up diskquotas.Disk quotas limit the amount of space an individual user can use.This feature is implemented in Windows 2000.Fixing the 2GB bugTheres really no re

41、ason why your scripts shouldnt report the true spaceeven on todays larger disks.To overcome the 2GB limitation,all you need todo is use the correct and up-to-date API functions.Just wrap them in a COMobject as outlined in Chapter 4.I have prepared a COM object for you thatcorrectly reports drive siz

42、es,demonstrating the use of API functions(seeFigure 7-4).To view the internal mechanics,open componentsfilesysfilesys.vbpin your Visual Basic CCE and compile the project.To just use the newmethods,install the software packageinstallfilesyssetup.exe.7-9.VBSset tool=CreateObject(“filesystem.tool”)free

43、=tool.FreeSpace(“C:”)total=tool.TotalSize(“C:”)msg=“Statistics Drive C:”&vbCrmsg=msg&“Free Space:“&fn(free)&vbCrmsg=msg&“Total Size:“&fn(total)226Part II:Conquering the File SystemII4684-8 ch07.f.qc 3/3/00 9:34 AM Page 226MsgBox msgfunction fn(bytes)fn=FormatNumber(bytes/10242,2)&“MB”end functionFig

44、ure 7-4:Your new COM object can deal with drives larger than 2GB.Calling file system APIs directlyThe filesystem.tool COMobject demonstrates some very important newtechniques.Have a look:Option Explicit old versionPrivate Declare Function GetDiskFreeSpace Lib“kernel32”_Alias“GetDiskFreeSpaceA”(ByVal

45、 lpRootPathName As String,_lpSectorsPerCluster As Long,lpBytesPerSector As Long,_lpNumberOfFreeClusters As Long,lpTotalNumberOfClusters As _Long)As Long new version without 2 GB limitation use Currency var type as“long integer”Private Declare Function GetDiskFreeSpaceEx Lib“kernel32”_Alias“GetDiskFr

46、eeSpaceExA”(ByVal lpRootPathName As String,_lpFreeBytesAvailableToCaller As Currency,lpTotalNumberOfBytes _As Currency,lpTotalNumberOfFreeBytes As Currency)As Long error code for undefined API functions:Private Const errNoSuchFunction=453Private Sub GetSizes(ByVal DriveLetter As String,TotalBytes As

47、Double,FreeBytes As Double)Dim drvLetter As StringDim free As CurrencyDim total As CurrencyDim allfree As CurrencyDim ok As IntegerDim lngSPC As Long sectors per clusterDim lngBPS As Long bytes per sectorDim lngTC As Long total number of clustersDim lngFC As Long free clustersTotalBytes=0FreeBytes=0

48、Chapter 7:Accessing the File System227II4684-8 ch07.f.qc 3/3/00 9:34 AM Page 227 was a valid drive letter specified?If Len(DriveLetter)=0 ThenErr.Raise vbObjectError+512+20,_“FileSystem Tool:Drive Size”,_“You did not specify a drive letter!”Exit SubEnd If transform letter in drive specs:drvLetter=UC

49、ase(Left(DriveLetter,1)&“:”valid drive letter?If Left(drvLetter,1)“Z”ThenErr.Raise vbObjectError+512+21,_“FileSystem Tool:Drive Size”,_“The specified drive letter“”&DriveLetter _&“”was invalid!”Exit SubEnd If API call is undefined on older systems with 2 GB limitation so catch errors!On Error Resume

50、 Nextok=GetDiskFreeSpaceEx(drvLetter,free,total,allfree)is new API call supported?If Err.Number=errNoSuchFunction Then no.This system can only use 2 GB max drives anyway,so use older version first turn back on error handling:Err.ClearOn Error GoTo 0 find out space infook=GetDiskFreeSpace(drvLetter,l

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 其他杂项

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁