Site icon SumTips

How to Copy or Move Files Selectively with PowerShell

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:

Exit mobile version