Copying Folders by Using WMI

Microsoft® Windows® 2000 Scripting Guide

Folders often need to be copied from one location to another. For example, you might copy a folder from one server to another to create a backup copy of that folder. Or you might have a templates folder that needs to be copied to user workstations, or a scripts folder that should be copied to all of your DNS servers.

The Win32_Directory Copy method enables you to copy a folder from one location to another, either on the same computer (for example, copying a folder from drive C to drive D) or on a remote computer. To copy a folder, you return an instance of the folder to be copied and then call the Copy method, passing as a parameter the target location for the new copy of the folder. For example, this line of code copies a folder to the Scripts folder on drive F:


WMI will not overwrite an existing folder when executing the Copy method. This means that the copy operation fails if the destination folder exists. For example, suppose you have a folder named Scripts and you attempt to copy that folder to a remote share named \\atl-fs-01\archive. If a folder named Scripts already exists on that share, the copy operation fails.

Scripting Steps

Listing 11.11 contains a script that copies the folder C:\Scripts to D:\Scripts. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to "impersonate."

  3. Use the ExecQuery method to query the Win32_Directory class.

    To limit data retrieval to a specified folder, a Where clause is included restricting the returned folders to those with the name C:\\Scripts. You must include both backslashes (\\) in the name.

  4. For the single folder in the returned collection, use the Copy method to copy the folder to D:\Archive. This procedure fails if the folder D:\Archive\Scripts already exists.

  5. Echo the results of the renaming procedure. A 0 indicates that the folder was successfully renamed.

Listing 11.11 Copying Folders Using WMI

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
 "SELECT * FROM Win_32 Directory WHERE Name = 'c:\\Scripts'")
For Each objFolder in colFolders
 errResults = objFolder.Copy("D:\Archive")
 Wscript.Echo errResults