Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003

Microsoft® Windows® 2000 Scripting Guide

« Previous | Next »   

Copying files, either from one folder to another on a single computer or from one computer to another, is a common administrative task. For example, you might want to copy a new monitoring script to all your servers or replace an outdated DLL with a newer version. The CopyFile method provides a way to perform these tasks programmatically.

The CopyFile method has two required parameters and one optional parameter:

The script in Listing 4.22 copies C:\FSO\ScriptLog.txt to the folder D:\Archive. This operation results in the existence of two files:

To ensure that the procedure will be carried out even if D:\Archive\ScriptLog.txt exists, the Overwrite parameter is set to True by using the constant OverWriteExisting.

Listing 4.22   Copying a File

1 2 3

Const OverwriteExisting = True Set objFSO = CreateObject("Scripting.FileSystemObject") objFSO.CopyFile "C:\FSO\ScriptLog.txt" , "D:\Archive\", OverwriteExisting

When specifying the destination folder, it is important to include the trailing backslash (for example, D:\Archive\). If the backslash is there, CopyFile will copy the file into the Archive folder. If the backslash is not there, CopyFile will try to create a new file named D:\Archive. If the folder D:\Archive already exists, a "Permission denied error" will be generated, and the copy procedure will fail.

The CopyFile method will also fail if you attempt to overwrite an existing read-only file, even if you have set the OverWrite parameter to True. To copy over a read-only file, you must first delete the file and then call the CopyFile method.

Copying a Set of Files

Wildcard characters provide a way to copy an entire set of files as long as these files are all in the same folder. You can copy a set of files using the same parameters used to copy a single file, but you must include a wildcard as part of the source parameter. For example, the script in Listing 4.23 copies all the .txt files found in C:\FSO to D:\Archive.

Listing 4.23   Copying a Set of Files

1 2 3

Const OverwriteExisting = True Set objFSO = CreateObject("Scripting.FileSystemObject") objFSO.CopyFile "C:\FSO\*.txt" , "D:\Archive\" , OverwriteExisting

Using wildcards with the CopyFile method allows you to copy all the files in a folder without copying any subfolders in that folder; the CopyFolder method, by contrast, copies both files and subfolders. The following code statement copies all the files in the C:\FSO folder without copying any subfolders:

objFSO.CopyFile "C:\FSO\*.*" , "D:\Archive\"


 Send us your feedback « Previous | Next »   

Категории