How to copy items from one location to another location using PowerShell?


To copy items in PowerShell, one needs to use the Copy-Item cmdlet. When you use the Copy-Item, you need to provide the source file name and the destination file or folder name.

In the below example, we will copy a single file from the D:\Temp to the D:\Temp1 location.

Example

Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru

Output

PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru
    Directory: D:\Temp1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       20-01-2020     12:10        1148809 PowerShellcommands.csv

In the above example, PowerShellCommands.csv file will be copied from the D:\Temp to the D:\Temp1 location. If the file already exists then it simply overwrites the file without any prompt or error or warning.

When you use the –Passthru parameter in the command, it displays the output in the console.

You can also rename items when you use the copy command. For that, you need to mention a new file name to the destination parameter.

Example

Copy-Item -Path D:\Temp\PowerShellcommands.csv 
-Destination D:\Temp1\PowerShel lcommands1.csv -PassThru

Output

PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\PowerShellcommands1.csv -PassThru
    Directory: D:\Temp1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       20-01-2020     12:10        1148809 PowerShellcommands1.csv

While copying item(s) to another location, their attributes are also copies with them.

When you copy files from the source folder to the destination folder, and if the destination folder doesn’t exist then files(s) won’t get copied and it will throw an exception of DirectoryNotFoundException.

Example

For example, we will copy the above mentioned PowerShellcommands1.csv file to the unknown destination folder D:\Temp2 as shown below.

Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShel
lcommands.csv -PassThru

Output

PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShellcommands.csv -PassThru
Copy-Item : Could not find a part of the path 'D:\Temp2\PowerShellcommands.csv'.
At line:1 char:1
+ Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand

Updated on: 12-Mar-2020

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements