An Introduction to Files and Folders in WSH - Working with Files and Folders
(Page 3 of 5 )
Okay, enumerating files and folders is all well and good, but let’s do something a little more useful. Chances are that if you are scripting files and folders you are most likely interested in performing actions on them. Common actions include moving, copying, and deleting. So let’s start there. As you probably expect, the FileSystemObject provides methods for doing all of these and more.
object.CreateTextFile Filename[, Overwrite[, Unicode]]
object.CreateFolder Foldername
object.DeleteFile File[, Force]
object.DeleteFolder Folder[, Force]
object.CopyFile Source, Destination[, Overwrite]
object.CopyFolder Source, Destination[, Overwrite]
object.MoveFile Source, Destination
object.MoveFolder Source, Destination
object.FileExists
object.FolderExists
We’re going to create a basic script that will create a folder and a add a couple of text files to it so that we have some files to work with.
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.CreateFolder("C:TestFolder")
For x = 1 to 5
strName = "test" & x & ".txt"
objFolder.CreateTextFile strName
Next
Now you should have a folder at C:TestFolder that has five text files named test1.txt through test5.txt. Now we’ll create a second folder called TestFolder2 and copy our text files to that location.
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objSrc = objFso.GetFolder("C:TestFolder")
Set objDest = objFso.CreateFolder("C:TestFolder2")
Set colFiles = objSrc.Files
For each file In colFiles
objFso.CopyFile file.Path, objDest.Path & "" & file.Name
Next
I’ve taken a little roundabout way of doing this so that I could demonstrate a few more properties and methods. You can see that I’ve constructed my file names and paths completely using the properties available to me. Just remember that all of these methods accept either objects or strings as their parameters and construct your code accordingly.
In this case, CopyFile accepts two string parameters. The first is the full path of our source file to copy, and the second is the full path to the destination. We pass our source with file.path. The path property returns a full path as a string so we can use that for our first parameter.
To avoid some confusion, this is what our properties actually return:
file.Path returns “C:\test.txt”
objDest.Path returns “C:\TestFolder2”
file.Name returns “text.txt”
The second parameter requires a full path to the destination file. Since we just created that folder, we need to construct a string to use. So we use the objDest.Path and file.Name properties. We’ve just concatenated them. Don’t forget to add the extra backslash (\) because objDest.Path does not return a trailing slash on our folder.
Next: Using the Sub-Objects >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer