4.10. Copying, Moving, or Renaming a File or Folder

Problem

You want to copy or move a set of files or folders to another location on the file system or to another server.

Solution

Using a graphical user interface

  1. Open Windows Explorer.

  2. In the left pane, browse to the parent folder of the file or folder you want to copy, move, or rename.

  3. In the right pane, right-click the file or folder.

    1. To rename, select Rename, enter the new name and hit Enter.

    2. To move or copy, select Cut or Copy, respectively. Browse to the new location, right-click in the folder, and select Paste.

Using a command-line interface

Moving, copying, and renaming files is pretty straightforward from the command line:

> move <Source> 
                  <Destination>
> copy <Source> 
                  <Destination>
> ren <Source> 
                  <Destination>

Using VBScript

' This code shows

 how to rename (same as move in WMI) and copy a file
' or folder. 
' ------ SCRIPT CONFIGURATION ------
strComputer = "."
strCurrentFile = "<CurrentFilePath>"  ' Path to existing file or folder
strNewFile     = "<NewFilePath>"      ' New path of file or folder
' ------ END CONFIGURATION ---------
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set objFile = objWMI.Get("Cim_Datafile='" & strCurrentFile & "'")
WScript.Echo "Renaming " & strCurrentFile & " to " & strNewFile
intRC = objFile.Rename(strNewFile)
if intRC <> 0 then
   WScript.Echo "There was an error renaming the file: " & intRC
else
   WScript.Echo "File rename successful"
end if
   
' ------ SCRIPT CONFIGURATION ------
strComputer = "."
strCurrentFile = "<CurrentFilePath>" ' Path to existing file or folder
strNewFile     = "<NewFilePath>"     ' Path to copy file or folder
' ------ END CONFIGURATION ---------
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set objFile = objWMI.Get("Cim_Datafile='" & strCurrentFile & "'")
WScript.Echo "Copying " & strCurrentFile & " to " & strNewFile
intRC = objFile.Copy(strNewFile)
if intRC <> 0 then
   WScript.Echo "There was an error copying the file: " & intRC
else
   WScript.Echo "File copy successful"
end if

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.