Windows batch scripting copy file

Batch file to copy files from one folder to another folder

I have a storage folder on a network in which all users will store their active data on a server. Now that server is going to be replaced by a new one due to place problem so I need to copy sub folders files from the old server storage folder to new server storage folder. I have below ex:

from \Oldeserver\storage\data & files to \New server\storage\data & files.

9 Answers 9

xcopy.exe is definitely your friend here. It’s built into Windows, so its cost is nothing.

Just xcopy /s c:\source d:\target

You’d probably want to tweak a few things; some of the options we also add include these:

  • /s/e — recursive copy, including copying empty directories.
  • /v — add this to verify the copy against the original. slower, but for the paranoid.
  • /h — copy system and hidden files.
  • /k — copy read-only attributes along with files. otherwise, all files become read-write.
  • /x — if you care about permissions, you might want /o or /x .
  • /y — don’t prompt before overwriting existing files.
  • /z — if you think the copy might fail and you want to restart it, use this. It places a marker on each file as it copies, so you can rerun the xcopy command to pick up from where it left off.

If you think the xcopy might fail partway through (like when you are copying over a flaky network connection), or that you have to stop it and want to continue it later, you can use xcopy /s/z c:\source d:\target .

Batch Script to copy files from a Text file

I need help with below code as it is executing in root folder only whereas I want the code to look for files within sub folders as well.

1 Answer 1

I suggest to use this command line in the batch file to copy all files with duplicating directory structure from source to destination directory.

It is assumed that the file documentation.txt contains a list of file names without path.

The command FOR reads one line after the other from file documentation.txt with skipping empty lines. The end of line character is modified from default ; to | using option eol=| to be able copying also files of which name starts unusually with a semicolon. No file name can contain a vertical bar anywhere. The line splitting behavior on spaces/tabs is disabled by using option delims= which defines in this case an empty list of string delimiters. Therefore file names with one or more space even at beginning of file name read from file are assigned unmodified to loop variable I . The option tokens=* removes leading spaces/tabs from the lines read from text file. A file name can begin with one or more spaces although such file names are unusual.

FOR runs for each file name the executable ROBOCOPY with directory of the batch file as source folder path and E:\Destination as destination folder path. ROBOCOPY interprets a \ left of one more \ or » as escape character. For that reason the source and destination folder paths should never end with a backslash as this would result in » being interpreted not as end of folder path, but everything up to next » in command line. For that reason . is appended to %

dp0 always expands to batch file folder path ending with a backslash. The dot at end of batch file folder path references the current folder of batch file folder. In other words with batch file stored in C:\Temp the batch file folder can be referenced with C:\Temp\ as done with %

dp0 but not possible with ROBOCOPY or with C:\Temp\. as done with %

dp0. or with just C:\Temp or with C:\Temp\\ as done with %

dp0\ which would also work with ROBOCOPY. See the Microsoft documentation about Naming Files, Paths, and Namespaces for details.

Читайте также:  Форматирование флешки под линукс

dp0 to use current folder as source folder instead of batch file folder.

The ROBOCOPY option /S results in searching in source folder and all its subfolders for the file and copy each found file to destination folder with duplicating the source folder structure in destination folder.

The other ROBOCOPY options are just for not printing list of created directories, list of copied files, header and summary.

Here is an alternative command line for this task copying all files from source directory tree into destination directory without creating subdirectories. So all copied files are finally in specified destination directory.

The inner FOR starts for each file name assigned to loop variable I of outer FOR one more command process in background with %ComSpec% /c and the DIR command line appended as additional arguments. So executed is for each file name in documentation.txt with Windows installed into C:\Windows for example:

The command DIR executed by second cmd.exe in background searches

  • in directory of the batch file
  • and all its subdirectories because of option /S
  • only for non-hidden files because of option /A-D-H (attribute not directory and not hidden)
  • with the specified file name
  • and outputs in bare format because of option /B
  • just the names of the found files with full path because of option /S .

It is possible that DIR cannot find a file matching these criteria at all in which case it would output an error message to handle STDERR of the background command process. This error message is suppressed by redirecting it with 2>nul to device NUL.

Read the Microsoft article about Using command redirection operators for an explanation of 2>nul . The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line in a separate command process started in background.

The inner FOR captures everything written to handle STDOUT of started background command process and processes this output line by line after started cmd.exe terminated itself after finishing execution of DIR.

The inner FOR assigns each full qualified file name to specified loop variable J without any modification because of option delims= and runs next the command COPY to copy that file as binary file to destination directory with automatically overwriting an existing file in destination directory with same file name. The success message output by COPY to handle STDOUT is redirected with >nul to device NUL to suppress it. An error message would be output by COPY. An error occurs if destination directory does not exist, or the destination directory is write-protected, or an existing file with same name is write-protected due to a read-only attribute or file permissions, or source file is opened by an application with sharing read access denied, or an existing destination file is opened by an application with sharing write access denied.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    call /? . for an explanation of %

Batch script for copying files based on name

Basically I want to write a little batch script that does the following — I have two folders, A and B. A has 10 files and B has 100. I want to compare the names of the files in each folder and if any in B have the same name as in A, then to copy them to folder A and overwrite the original file.

I was trying to start off by doing a «for» command on folder A but then I would have to follow that with an IF to compare the filenames which I have no idea how to express correctly

Sry but I am useless with batch scripting. I found a couple of threads covering similar questions, but rly didn’t follow the answers enough to help.

Читайте также:  What is linux clusters

Is this difficult? The other threads comparing two filenames looked kinda complicated.

Thanks for any help 🙂

modifiers. Also the nearly forgotten help replace still exists – user6811411 Nov 17 ’18 at 10:45

1 Answer 1

  • /s copies folders and subfolders
  • /u copies only file that pre-exist in both folders
  • /y suppresses prompts on overwriting files
  • /i tells xcopy that destination is a folder
  • /r ignores READONLY attribute just in case (this is optional)
  • /c continues copying even if errors occur (this is optional)

More information on xcopy can be found here (or xcopy /? )

If that does not work for you then something like this should do:

Here is what it does:

  • if exist checks if a file exists
    • the path it checks is composed from folderA path and name and extension of the file found in folderB
  • copy /y copies file overwriting existing one
    • from original file found in folderB
    • to similar-named file found in folderA

dpnxa syntax goes like this:

    %%SOMETHINGa means this is a for-loop variable

suppresses double quotes around file names (we will provide our own ones)

  • d is for disk ( c: )
  • p is for path to containing folder ( \folderA\ )
  • n is for name of the file (i.e. readme )
  • x is for extension (i.e. .txt )
  • You can mix and match those as you like. More info is here or try for /?

    If logic needs to be more complicated I suggest either using ( ) brackets + delayed expansion or call :label ( call /? )

    UPDATE: Corrected mixup of FolderA and FolderB

    Windows batch scripting copy file

    Copies one or more files from one location to another.

    You can also use the copy command, with different parameters, from the Recovery Console. For more information about the recovery console, see Windows Recovery Environment (Windows RE).

    Syntax

    Parameters

    Parameter Description
    /d Allows the encrypted files being copied to be saved as decrypted files at the destination.
    /v Verifies that new files are written correctly.
    /n Uses a short file name, if available, when copying a file with a name longer than eight characters, or with a file name extension longer than three characters.
    /y Suppresses prompting to confirm that you want to overwrite an existing destination file.
    /-y Prompts you to confirm that you want to overwrite an existing destination file.
    /z Copies networked files in restartable mode.
    /a Indicates an ASCII text file.
    /b Indicates a binary file.
    Required. Specifies the location from which you want to copy a file or set of files. Source can consist of a drive letter and colon, a directory name, a file name, or a combination of these.
    Required. Specifies the location to which you want to copy a file or set of files. Destination can consist of a drive letter and colon, a directory name, a file name, or a combination of these.
    /? Displays help at the command prompt.

    Remarks

    You can copy an ASCII text file that uses an end-of-file character (CTRL+Z) to indicate the end of the file.

    If /a precedes or follows a list of files on the command line, it applies to all files listed until copy encounters /b. In this case, /b applies to the file preceding /b.

    The effect of /a depends on its position in the command-line string: — If /a follows source, the copy command treats the file as an ASCII file and copies data that precedes the first end-of-file character (CTRL+Z). — If /a follows destination, the copy command adds an end-of-file character (CTRL+Z) as the last character of the file.

    If /b directs the command interpreter to read the number of bytes specified by the file size in the directory. /b is the default value for copy, unless copy combines files.

    If /b precedes or follows a list of files on the command line, it applies to all listed files until copy encounters /a. In this case, /a applies to the file preceding /a.

    The effect of /b depends on its position in the command–line string: — If /b follows source, the copy command copies the entire file, including any end-of-file character (CTRL+Z). — If /b follows destination, the copy command doesn’t add an end-of-file character (CTRL+Z).

    If a write operation cannot be verified, an error message appears. Although recording errors rarely occur with the copy command , you can use /v to verify that critical data has been correctly recorded. The /v command-line option also slows down the copy command, because each sector recorded on the disk must be checked.

    If /y is preset in the COPYCMD environment variable, you can override this setting by using /-y at the command line. By default, you are prompted when you replace this setting, unless the copy command is executed in a batch script.

    To append files, specify a single file for destination, but multiple files for source (use wildcard characters or file1+file2+file3 format).

    If the connection is lost during the copy phase (for example, if the server going offline breaks the connection), you can use copy /z to resume after the connection is re-established. The /z option also displays the percentage of the copy operation that is completed for each file.

    You can substitute a device name for one or more occurrences of source or destination.

    If destination is a device (for example, Com1 or Lpt1), the /b option copies data to the device in binary mode. In binary mode, copy /b copies all characters (including special characters such as CTRL+C, CTRL+S, CTRL+Z, and ENTER) to the device, as data. However, if you omit /b, the data is copied to the device in ASCII mode. In ASCII mode, special characters might cause files to combine during the copying process.

    If you don’t specify a destination file, a copy is created with the same name, modified date, and modified time as the original file. The new copy is stored in the current directory on the current drive. If the source file is on the current drive and in the current directory and you do not specify a different drive or directory for the destination file, the copy command stops and displays the following error message:

    If you specify more than one file in source, the copy command combines them all into a single file using the file name specified in destination. The copy command assumes the combined files are ASCII files unless you use the /b option.

    To copy files that are 0 bytes long, or to copy all of a directory’s files and subdirectories, use the xcopy command.

    To assign the current time and date to a file without modifying the file, use the following syntax:

    Where the commas indicate that the destination parameter has been intentionally left out.

    Examples

    To copy a file called memo.doc to letter.doc in the current drive and ensure that an end-of-file character (CTRL+Z) is at the end of the copied file, type:

    To copy a file named robin.typ from the current drive and directory to an existing directory named Birds that is located on drive C, type:

    If the Birds directory doesn’t exist, the file robin.typ is copied into a file named Birds that is located in the root directory on the disk in drive C.

    To combine Mar89.rpt, Apr89.rpt, and May89.rpt, which are located in the current directory, and place them in a file named Report (also in the current directory), type:

    If you combine files, the copy command marks the destination file with the current date and time. If you omit destination, the files are combined and stored under the name of the first file in the list.

    To combine all files in Report, when a file named Report already exists, type:

    To combine all files in the current directory that have the .txt file name extension into a single file named Combined.doc, type:

    To combine several binary files into one file by using wildcard characters, include /b. This prevents Windows from treating CTRL+Z as an end-of-file character. For example, type:

    If you combine binary files, the resulting file might be unusable due to internal formatting.

    Читайте также:  Xerox 3220 драйвера для mac os
    Оцените статью