Windows XP Annoyances Free Open Book

Windows XP Annoyances

Previous PageNext Page

9.4 Manipulating Files from Scripts

One of the myths surrounding the Windows Script Host, and VBScript in particular, is that there's no provision for accessing the filesystem (copying, deleting, and writing to files). This assumption is based on the fact that VBScript, when used in web pages, is not permitted to access the filesystem for security reasons.

The following routines, all of which rely on the FileSystemObject object, should provide most necessary file operations. The names I've chosen for these functions and subroutines are based on what they act upon and what they're used for; for example, the FolderCopy subroutine is used to copy a folder, and the FileCopy subroutine is used to copy a file.

The following two functions return properties of drives—whether a specific drive letter exists and how much free space a specified drive has, respectively:

Function DriveExists(DriveLetter)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  DriveExists = FileObject.DriveExists(DriveLetter)
End Function
  
Function DriveFreeSpace(DriveLetter)
  If Left(DriveLetter,1) <> ":" Then DriveLetter = DriveLetter & ":"
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set DriveHandle = _ 
                FileObject.GetDrive(FileObject.GetDriveName(DriveLetter))
  DriveFreeSpace = DriveHandle.FreeSpace
End Function 

These next seven subroutines and functions are used to manipulate folders. The functions are used to retrieve information about a folder, and the subroutines are used to perform actions on a folder. The arguments should all be full folder names (e.g., "D:\Documents and Settings\All Users\Desktop"). Note that the FolderSize function returns the combined size of all the contents of a folder, including all subfolders, and may take a few seconds to return a result for large folders. You may want to use the FolderExists function before any others to prevent errors:

Sub FolderCopy(Source, Destination)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileObject.CopyFolder Source, Destination
End Sub

Function FolderCreate(Foldername)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set Result = FileObject.CreateFolder(FolderName)
  If Result.Path = "" Then
    FolderCreate = False   'failure
  Else
    FolderCreate = True    'success
  End If
End Function

Sub FolderDelete(Foldername)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileObject.DeleteFolder(Foldername)
End Sub

Function FolderExists(Foldername)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FolderExists = FileObject.FolderExists(Foldername)
End Function

Sub FolderMove(Source, Destination)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileObject.MoveFolder Source, Destination
End Sub

Function FolderSize(Foldername)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set FolderHandle = FileObject.GetFolder(Foldername)
  FolderSize = FolderHandle.Size
End Function  

Function FolderParent(Foldername)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FolderParent = FileObject.GetParentFolderName(Foldername)
End Function

These next seven subroutines and functions are used to manipulate files, and are similar to the folder counterparts listed above. And likewise, the functions are used to retrieve information about a file, and the subroutines are used to perform actions on a file. The arguments should all be fully qualified filenames (e.g., "c:\windows\notepad.exe"). You may want to use the FileExists function before any others to prevent errors:

Sub FileCopy(Source, Destination)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileObject.CopyFile Source, Destination
End Sub

Function FileDate(Filename)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set FileHandle = FileObject.GetFile(Filename)
  GetFileDate = FileHandle.DateCreated
End Function 

Sub FileDelete(Filename)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileObject.DeleteFile(Filename)
End Sub

Function FileExists(Filename)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileExists = FileObject.FileExists(Filename)
End Function

Function FileExtension(Filename)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  GetFileExtension = FileObject.GetExtensionName(Filename)
End Function

Sub FileMove(Source, Destination)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  FileObject.MoveFile Source, Destination
End Sub

Function FileSize(Filename)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set FileHandle = FileObject.GetFile(Filename)
  FileSize = FileHandle.Size
End Function  

This next two functions can be used on either files or folders and allow you to retrieve and set file attributes (Archive, Read-Only, System, and Hidden, respectively).

File attributes are specified numerically: Read-Only = 1, Hidden = 2, System = 4, and Archive = 32. So, to set the Hidden and System attributes for a file, the Attrib parameter would be set to 6 (or 2+4). To read a file's attributes, the same constants are used, but only individually. For example, to see if a file had, say, the System attribute turned on, you would use this statement: If GetAttributes("c:\somefile.txt",4) = True Then Msgbox "This is a system File." :

Function GetAttributes(Filename, Attrib)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set FileHandle = FileObject.GetFile(Filename)
  If FileHandle.Attributes And Attrib Then
    GetAttributes = True
  Else
    GetAttributes = False
  End If
End Function

Sub SetAttributes(Filename, Attrib)
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set FileHandle = FileObject.GetFile(Filename)
  FileHandle.Attributes = Attrib
End Sub

The following four functions are used to obtain the locations of special Windows folders, or, in the case of GetTempFilename, to generate a new filename in the current user's Temp folder. (Rather than simply returning the location of the Temp folder, the GetTempFilename function returns the full path of a newly-generated temporary filename. The corresponding file is guaranteed not to exist, so you can use it for the purposes of temporary storage without fear of conflicting with another open application.)

So, for example, to get the full path of the current user's Desktop folder, you would use GetSpecialFolder("Desktop"). The folders accessible with this function include AllUsersDesktop, AllUsersStartMenu, AllUsersPrograms, AllUsersStartup, Desktop, Favorites, Fonts, MyDocuments, NetHood, PrintHood, Programs, Recent, SendTo, StartMenu, Startup, and Templates. See Section 9.16 later in this chapter for several examples.

Function GetSpecialFolder(Foldername)
  set WshShell = WScript.CreateObject("WScript.Shell")
  GetSpecialFolder = WshShell.SpecialFolders(Foldername)
End Function

Function GetSystemFolder(  )
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  GetSystemFolder = FileObject.GetSpecialFolder(1) & "\"
End Function

Function GetTempFilename(  )
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  GetTempFile = FileObject.GetSpecialFolder(2) & "\" _
                & FileObject.GetTempName
End Function

Function GetWindowsFolder(  )
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  GetWindowsFolder = FileObject.GetSpecialFolder(0) & "\"
End Function

While the previous functions and subroutines are used to manipulate files, the following two are used to manipulate the contents of files. The ReadFromFile function will transfer the contents of any file into a variable (naturally, this is most useful with plain-text files). Likewise, the WriteToFile subroutine will transfer the contents of a variable (specified as "Text") into a file. If the file doesn't exist, it will be created; if the file already exists, the text will be appended to the end of the file:

Function ReadFromFile(Filename)
  Const ForReading = 1, ForWriting = 2, ForAppending = 8
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  Set FileHandle = FileObject.OpenTextFile(Filename, ForReading)
  Buffer=""
  Do Until FileHandle.AtEndOfStream
    Buffer = Buffer & FileHandle.ReadLine & vbCrLf
  Loop
  FileHandle.Close
  ReadFromFile = Buffer
End Function

Sub WriteToFile(Filename, Text)
  Const ForReading = 1, ForWriting = 2, ForAppending = 8
  Set FileObject = CreateObject("Scripting.FileSystemObject")
  If FileObject.FileExists(Filename) Then
    Set FileHandle = FileObject.OpenTextFile(Filename, _
                                             ForAppending)
    FileHandle.Write vbCrLf
  Else
    Set FileHandle = FileObject.CreateTextFile(Filename)
  End If
  FileHandle.Write Text
  FileHandle.Close
End Sub

The use of all of the "file operations" subroutines and functions listed earlier should be fairly self-explanatory, and they all work similarly. For example, the FolderExists function and the FileExists function are both nearly identical, except that FolderExists checks for the existence of a folder, while FileExists checks for the existence of a single file. See the Section 9.16.5 example script at the end of this chapter for additional examples, as well as a method for obtaining a list of all the files in a given folder.

Previous PageNext Page


     Main Menu
Cover
Copyright
Preface
Chapter 1. Making the Most of Windows XP
Chapter 2. Basic Explorer Coping Skills
Chapter 3. The Registry
Chapter 4. Tinkering Techniques
Chapter 5. Maximizing Performance
Chapter 6. Troubleshooting
Chapter 7. Networking and Internetworking
Chapter 8. User Accounts and Administration
Chapter 9. Scripting and Automation
9.1 Building a Script with VBScript
9.2 Running Applications from Scripts
9.3 Accessing the Registry from Scripts
9.4 Manipulating Files from Scripts
9.5 Creating Windows Shortcuts and Internet Shortcuts in Scripts
9.6 Networking with Scripts
9.7 Manipulating Internet Explorer from Scripts
9.8 Using Command-Line Parameters in Scripts
9.9 Managing Services with Scripts
9.10 Writing CGI Scripts for a Web Server
9.11 Making a Startup Script
9.12 Deciphering Script Errors
9.13 Finding a Better Editor
9.14 Further Study
9.15 Automating Scripts with Scheduled Tasks
9.16 Wacky Script Ideas
Chapter 10. Installing Windows XP
Appendix A. Setting Locator
Appendix B. BIOS Settings
Appendix C. Command Prompt Crash Course
Appendix D. TCP/IP Ports
Appendix E. Error Messages (Blue Screen of Death)
Colophon


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele