Moving Folders by Using the Rename Method

Microsoft® Windows® 2000 Scripting Guide

The Win32_Directory class does not provide a one-step method for moving folders. Instead, moving a folder generally involves two steps:

  1. Copying the folder to its new location

  2. Deleting the original folder

The one exception to this two-step process involves moving a folder to a new location on the same drive. For example, suppose you want to move C:\Temp to C:\Scripts\Temporary Files\Archive. As long as the current location and the new location are on the same drive, you can move the folder by simply calling the Rename method and passing the new location as the method parameter. This approach effectively allows you to move the folder in a single step. However, the script fails if the current drive and the new drive are different. An attempt to rename C:\Temp to D:\Temp fails with a "Drive not the same" error.

Scripting Steps

Listing 11.10 contains a script that moves the folder C:\Scripts to C:\Admins\Documents\Archive\VBScript. 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 Rename method to move the folder to C:\Admins\Documents\Archive\VBScript.

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

Listing 11.10 Moving Folders Using WMI

  
1
2
3
4
5
6
7
8
9
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_Directory WHERE Name = 'c:\\Scripts'")
For Each objFolder in colFolders
 errResults = objFolder.Rename("C:\Admins\Documents\Archive\VBScript")
 Wscript.Echo errResults
Next