Export (0) Print
Expand All

Renaming Files

Microsoft® Windows® 2000 Scripting Guide

It is not unusual for files to be given new names. Sometimes this is done to provide a file with a more descriptive name (for example, changing 03b4cast.xls to Budget Forecast for 2003.xls). At other times, this is done to ensure that data is not lost or that other operations can proceed. For example, you might have a script that backs up the Application event log to a file named ApplicationBackup.evt. If that file already exists, the backup operation fails. Consequently, you might want to rename the existing version of ApplicationBackup.evt before running the backup script. This, and any other renaming operation, can be carried out using the CIM_Datafile Rename method.

When renaming a file, you must specify the complete path name. For example, to rename a file in the C:\Scripts\Logs folder, you must include the entire path name as the parameter:

errResult = objFile.Rename("C:\Scripts\Logs\NewName.vbs")

Passing only the file name results in an error. For example, this line of code results in an "Invalid name" error:

errResult = objFile.Rename("NewName.vbs")

Scripting Steps

Listing 11.23 contains a script that renames a file. 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 CIM_DataFile class.

    To limit data retrieval to a specific file, a Where clause is included restricting the returned files to those with the file name c:\\scripts\\toggle_service.vbs. You must include both backslashes in the query.

  4. For the single file in the collection, use the Rename method to rename the file c:\scripts\toggle_service.old, and then echo the results of that procedure. A 0 indicates that the file was successfully renamed.

Listing 11.23 Renaming Files


strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
 ("SELECT * FROM Cim_Datafile WHERE Name = " _
 & "'c:\\scripts\\toggle_service.vbs'")
For Each objFile in colFiles
 errResult = objFile.Rename("c:\scripts\toggle_service.old")
 Wscript.Echo errResult

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft