Powershell copy files from directory excluding certain extensions

In Powershell you can use the pipe symbol “|” to chain certain commands together. This enables you to make powerful scripts. One example how you can use this is to recursively copy files from one location to another, but exclude certain files based on the filename or extension.

Example 1: copy all files from one folder to another with no exclusion (recursively)

The following example will simply copy all files from “D:\dir1” to “D:\dir2”. There is no exclusion filter applied here.

Get-ChildItem -Path D:\dir1 | Copy-Item -Destination D:\dir2 -Recurse -Container -Force -PassThru

Example 2: copy all files except files with a “.config” extension

The snippet below does the same as example #1, however now we added a check that only takes objects where the extension IS NOT equal to “.config”.

Get-ChildItem -Path D:\dir1 | Where-Object{$_.extension -notin ".config"} | Copy-Item -Destination D:\dir2 -Recurse -Container -Force -PassThru

In the “Where-Object{$.” part you can play around with different properties to check for such as filenames, file extensions etc. (Check the autocomplete in the Powershell editor).

Good luck!

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published.