25

I am using Powershell v 2.0. and copying files and directories from one location to another. I am using a string[] to filter out file types and also need to filter out a directory from being copied over. The files are being filtered out correctly, however, the directory I am trying to filter obj keeps being copied.

$exclude = @('*.cs', '*.csproj', '*.pdb', 'obj')
    $items = Get-ChildItem $parentPath -Recurse -Exclude $exclude
    foreach($item in $items)
    {
        $target = Join-Path $destinationPath $item.FullName.Substring($parentPath.length)
        if( -not( $item.PSIsContainer -and (Test-Path($target))))
        {
            Copy-Item -Path $item.FullName -Destination $target
        }
    }

I've tried various ways to filter it, \obj or *obj* or \obj\ but nothing seems to work.

Thanks for any assistance.

Flea
  • 11,176
  • 6
  • 72
  • 83

3 Answers3

57

The -Exclude parameter is pretty broken. I would recommend you to filter directories that you don't want using Where-Object (?{}). For instance:

$exclude = @('*.cs', '*.csproj', '*.pdb')
$items = Get-ChildItem $parentPath -Recurse -Exclude $exclude | ?{ $_.fullname -notmatch "\\obj\\?" }

P.S.: Word of warning – don't even think about using -Exclude on Copy-Item itself.

Dr1Ku
  • 2,875
  • 3
  • 47
  • 56
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • Thanks! Worked like a charm! – Flea Nov 07 '13 at 18:08
  • If you're looking for a POSH 5.0 example or a way to handle multiple excludes, take a look at this answer: http://stackoverflow.com/a/35993562/615422 – VertigoRay May 10 '16 at 21:22
  • What is the role of "$_.fullname -notmatch '//obj//' here ? Sorry i am new to powershell wildcards. – Moose Aug 03 '17 at 17:45
  • 1
    Upvote for "The -Exclude parameter is pretty broken" because it is, and you're the first/only one who's diagnosed the problem. Thanks. – Sabuncu Oct 23 '17 at 17:17
7

I use this to list files under a root but not include the directories

$files = gci 'C:\' -Recurse  | Where-Object{!($_.PSIsContainer)}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Stuzc
  • 71
  • 1
  • 1
4
Get-ChildItem -Path $SourcePath -File -Recurse | 
Where-Object { !($_.FullName).StartsWith($DestinationPath) } 
Bjorn Mistiaen
  • 6,459
  • 3
  • 18
  • 42