Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Use PowerShell to copy all files with a certain name or extension

Use this simple PowerShell script to batch copy files from one location to another on your computer.

A manager at work recently asked me to provide him with a copy of some Excel data files. Unfortunately those data files were scattered amongst 40 different directories. Locating them all and then copying them to another directory would be a massive chore.

Thankfully PowerShell came to the rescue.

The following script has three parameters that need to be specified:

In the example below, files need to have either the word “research” in their name or or the .xlsx file extension to be copied. The $files parameter can be adjusted to include as many rules as are required. The directory c:\files will be searched and any matching files copied to f:\archive.

$source="c:\files" #location of starting directory
$destination="f:\archive"; #location where files will be copied to
$files=@("*research*", "*.xlsx")

New-Item -ItemType Directory -Force -Path ($destination); Get-ChildItem -recurse ($source) -include ($files) | Copy-Item -Destination ($destination)

The source directory will be recursed by default. Simply remove the -recurse command if this is not desired.

Note

If your destination directory is located within the source directory, then a “Cannot copy item onto itself” error will be displayed in PowerShell. Even if this occurs and the errors are displayed, the script will still work.

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.