Skip to content

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

G2nd September 2015

CNo Comments

TPowerShell, Windows

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:

  • $source = The source directory of the files
  • $destination = The destination to where they will be copied
  • $files = The parameter(s) that the file names need to meet in order to be copied

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.