Copying Files and Folders

The Copy-Item cmdlet enables you to copy objects from one path to another. The following command creates a backup by copying the file users.xlsx from one remote computer (fs) and saving it to another (fs2) over the network:

Copy-Item -Path \\fs\Shared\it\users.xlsx -Destination \\fs2\Backups\it\users.xlsx

If the target file already exists, the copy attempt will fail. To overwrite the existing file, even if it is in Read-Only mode, use the -Force parameter:

Copy-Item -Path \\fs\Shared\it\users.xlsx -Destination \\fs2\Backups\it\users.xlsx -Force

If you’re copying files to or from remote computers, be sure to use UNC paths. To copy files from your local directory to the remote folder, simply reverse the source and destination locations:

Copy-Item C:\data\ -Recurse \\fs\c$\temp

You can also copy files from one remote server to another. The following script recursively copies the \\fs\Shared\temp folder to \\fs\Shared\test:

Copy-Item \\fs\Shared\temp -Recurse \\fs\Shared\test

To copy only certain files from the source content to the destination, use the -Filter parameter. For instance, the following command copies only txt files from one folder to another:

Copy-Item -Filter *.txt -Path \\fs\Shared\it -Recurse -Destination \\fs2\Shared\text

You can also run the XCOPY and ROBOCOPY commands to copy files, or use COM objects as in the example below:

(New-Object -ComObject Scripting.FileSystemObject).CopyFile('\\fs\Shared', 'fs2\Backup')