PowerShell With Robocopy and Arguments Passing

You can use several tools to copy files and directories in PowerShell. Robocopy
is a popular command-line utility in Windows to copy file data from one location to another.
It is a powerful command that can copy a large file data volume. This tutorial will teach you to use robocopy
in PowerShell.
Use the robocopy
Command to Copy Files in PowerShell
The general syntax of robocopy
command is:
robocopy <source> <destination> [<file>] [<options>]
The following is a simple robocopy
command example.
robocopy C:\New C:\pc car.png /njh /njs
It copies a car.png
file from the C:\New
directory to the C:\pc
directory. The /njh
option hides the job header, and the /njs
option hides the job summary.
Output:
1 C:\New\
New File 3465 car.png
98%
100%
For more information on robocopy
options, read this article.
Let’s have a look at another robocopy
command example. The following variables store the value for the robocopy
arguments.
$source = "C:\New\complex"
$destination = "C:\pc\computing"
$robocopyOptions = "/njh"
$file = "report.docx"
This command copies a report.docs
file from the source directory C:\New\complex
to the destination directory C:\pc\computing
.
robocopy $source $destination $file $robocopyOptions
Output:
1 C:\New\complex\
New File 1.5 m report.docx
15%
31%
47%
63%
79%
95%
100%
------------------------------------------------------------------------------
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1 0 1 0 0 0
Files : 1 1 0 0 0 0
Bytes : 1.56 m 1.56 m 0 0 0 0
Times : 0:00:00 0:00:00 0:00:00 0:00:00
Speed : 41,05,59,250 Bytes/sec.
Speed : 23,492.389 MegaBytes/min.
Ended : 21 May 2022 12:53:25
The above command will not work when you store multiple options in the $robocopyOptions
variable.
$robocopyOptions="/njh /njs"
You have to split the strings in the command like this.
robocopy $source $destination $file $robocopyOptions.split(' ')
Output:
1 C:\New\complex\
New File 1.5 m report.docx
15%
31%
47%
63%
79%
95%
100%
Robocopy
is a useful tool for copying a large volume of files. It is an excellent choice if you are looking for a simple way to copy or move files in PowerShell.