PowerShell: Use Copy-Item and Exclude Folders


Often you may want to use the Copy-Item cmdlet in PowerShell to copy folders to a new directory but exclude specific folders from being copied.

You can use the following syntax to do so:

$source = "c:\users\bobbi\data3"
$destination = "c:\users\bobbi\data4"

New-Item -ItemType Directory -Force -Path $destination
Copy-Item $source\* $destination -Exclude @("*old*","baseball") -Recurse

This particular example copies all folders from the data3 directory into the data4 directory, excluding any folders that contain “old” anywhere in the name and excluding the folder named “baseball”.

The following example shows how to use this syntax in practice.

Example: Use Copy-Item and Exclude Folders in PowerShell

Suppose that we have a directory located at the following path:

  • C:\Users\bobbi\data3

We can type Dir to list out all files in this directory:

Suppose that we would like to copy all files from the data3 directory into the data4 directory, excluding any folders that contain “old” anywhere in the name and excluding the folder named “baseball”.

We can use the following syntax to do so:

$source = "c:\users\bobbi\data3"
$destination = "c:\users\bobbi\data4"

New-Item -ItemType Directory -Force -Path $destination
Copy-Item $source\* $destination -Exclude @("*old*","baseball") -Recurse

The following screenshot shows how to use this syntax in practice:

PowerShell copy-item exclude folders

We can see that we’re able to successfully copy all folders from the data3 directory into the data4 directory, excluding the following folders:

  • All folders with “old” in the folder name
  • The folder named “baseball”

Note #1: We used wildcard characters ( * ) to indicate that any folder with “old” anywhere in the name should be excluded from being copied.

Note #2: In this example we specified two patterns in the -Exclude array but you can specify as many patterns as you’d like to exclude even more folders from being copied.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Copy and Rename a File
PowerShell: How to Use Copy-Item and Create New Directory
PowerShell: How to Rename File Extension of Multiple Files

Leave a Reply