...Because someone's gotta tell the story...


To return to the main Blog List, click Full Blog Listing.



Renaming a file remotely via VBScript and WMI

Wednesday, November 24, 2010 in Technical Articles (Views: 2471)
I'm not an enterprise, so I don't have seemingly endless resources to throw at technology. We do run the computers in our home much like a business, as the motto of has always been: A hobbyist project gone way overboard (mission accomplished I would say). One such tool I've automated is NTBackup (yes, into an enterprise ready solution). The NTBackup piece will be in another blog someday, but for now, I wanted to show you a quick and dirty way to use VBScript to rename a file on a remote machine, as opposed to copying a file, which can, depending on the size of the file and bandwidth, take considerably longer.

Note: For those searching, seach no longer. This is the renfiles.vbs script.

Since I use this script in other scripts, I rely on command line arguments to provide the input to the script. Here is a sample syntax to run the script, renaming the file test.txt to test.old in the c:\temp directory on Server1:

cscript renfiles.vbs Server1 c:\temp\test.txt c:\temp\test.old

Without further delay, the script, with commentary.

'First, we need to give the computer that we are renaming the file on.
strComputer = wscript.arguments(0)
'The WScript.echo statements are nothing more than display, to make sure that your arguments passed are correct. This is just for troubleshooting.
wscript.echo "Connecting to computer: " & wscript.arguments(0)

'Here we make a connection to the remote server via WMI
Set objWMIService = GetObject ("winmgmts:" & "!\\" & strComputer & "\root\cimv2")

'Now, we are building a query. You are supposed to put a \\ instead of a \ for the local path
'Example: c:\temp is really c:\\temp. I changed the code (note the replace statement) to accomodate this automatically. This is just for those who take it to the next level by manually testing using wbemtest.

dim strWMI
strWMI="Select * from CIM_DataFile where Name = '" + replace(wscript.arguments(1),"\","\\") + "'"
wscript.echo strWMI

'Execute the Query and return the results.
Set colFiles = objWMIService.ExecQuery (strWMI)
For Each objFile in colFiles
'Just a side note, unlike the original query, you do not have to use the double backslash when renaming the file.
'If you are manually running the script and do not see the "Renaming file to" portion, check the name you are searching for above or manually test your query in wbemtest.
wscript.echo "Renaming file to " & wscript.arguments(2)
errResult = objFile.Rename(wscript.arguments(2))

Hope you find this script useful - it has worked great in my backup scripts..


Related Blogs You May Be Interested In:

To leave a comment, please log in and/or register.