How to Copy or Move Files Selectively with PowerShell

Print Page

In this post we will see how to copy and move files and folders selectively with PowerShell. We are going to use Copy-Item cmdlet with a few switch parameters for copying files. Similarly, with Move-Item cmdlet, you can use all the examples below for moving the desired files.
Copy-Item Powershell

1. Copy File with Copy-Item cmdlet

Copy-Item C:\Source\Test.txt C:\Destination

This simple script will copy “Test.txt” file from the “Source” directory to “Destination” directory.

2. Recursively Copy Sub-Directories with Copy-Item cmdlet

Copy-Item C:\Source\* C:\Destination -recurse

-recurse parameter recursively searches for all files and folders within “Source” directory.

3. Copy Files from Multiple Directories and Merge into One Folder

Copy-Item C:\Source\A\*, C:\Source\B\* C:\Destination

This would create a flat folder structure by copying all files from directory “A” and “B” and paste the files into “Destination” folder.

4. Exclude Particular File Type from Copy

Copy-Item C:\Source\ C:\Destination -recurse -exclude *.txt

This would exclude all Text files, including sub-directories, from being copied.

5. Exclude a Particular File Type with Specific Name from Copy operation

Copy-Item C:\Source\ C:\Destination -recurse -exclude [a-d]*.txt

This would exclude all “txt” files that matches wild card pattern [a-d].

6. Copy Files Based on Filename Prefix

Copy-Item C:\Source C:\Destination -filter DSC_* -recurse

This would copy only those files which start with prefix “DSC_”

7. Copy Files Containing Particular Keyword

Get-ChildItem C:\Source -recurse -filter '*DSC*.jpg' | Copy-Item -destination C:\Destination

This would copy all files which has “DSC” anywhere in their name and is of type “JPG.”

8. Copy Files Without Preserving Directory Structure

We can perform more complex copy and move operations by piping the results of the Get-ChildItem cmdlet to the Copy-Item and Move-Item cmdlets.

Get-ChildItem C:\Source -recurse -force -filter "Aa*" | Copy-Item C:\Destination

This would create a flat folder structure by copying all files starting with “Aa” to the root of “Destination” directory.

Some optional parameters:

  • –whatif: With this parameter you can verify the result of a particular copy or move operation without actually executing it. Files are not moved until you run the cmdlet by removing –whatif parameter.
  • -verbose: With this parameter you can view the output of each file operation in the console.
  • -force: By default copy and move operation will not overwrite a file. With this parameter you can force the override of an existing item or a read-only system file.