Exclude multiple Directories while using Copy-Item

Objective: Copy all subfolder contents in C:\TestEnv to itself.

From

C:\TestEnv\Folder1\*
C:\TestEnv\Folder1\Testfile1.txt
C:\TestEnv\Folder1\Testfile2.tpdf
C:\TestEnv\Folder2\*
C:\TestEnv\Folder2\Testfile3.txt
C:\TestEnv\Folder2\Testfile4.pdf

To

C:\TestEnv\
C:\TestEnv\Testfile1.txt
C:\TestEnv\Testfile2.tpdf
C:\TestEnv\Testfile3.txt
C:\TestEnv\Testfile4.pdf

What I have so far...

$Exclude = 'C:\TestEnv\Scripts','C:\TestEnv\TestFiles'
Copy-Item -Exclude $Exclude -Path "C:\TestEnv\*\*" -Destination "C:\TestEnv" -Recurse

1 Answer

Since, -Exclude doesn't get arrays, Try this:

$Exclude = 'C:\TestEnv\Scripts','C:\TestEnv\TestFiles'
Get-ChildItem -Path "C:\TestEnv\*" -directory | where {$_.fullname -notin $Exclude} | Get-ChildItem -Recurse -File | Foreach { Copy-Item -LiteralPath $_.Fullname -Destination "C:\TestEnv\" -force }

Here:

  • Define Exclusion array as $Exclude.
  • Filter directories from source using Get-ChildItem and -Directory switch.
  • Filter the exclusion directories with where.
  • Again list only files with -File and recursive with -Recurse.
  • Then Copy-Item forcefully (-Force omittable) in a Foreach loop piped the files.
9

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like