Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to exclude directory using Get-ChildItem -Exclude parameter in Powershell

Tags:

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.

like image 774
Flea Avatar asked Nov 07 '13 17:11

Flea


People also ask

How do I get-ChildItem in PowerShell?

The Get-ChildItem cmdlet uses the Path parameter to specify the directory C:\Test . Get-ChildItem displays the files and directories in the PowerShell console. By default Get-ChildItem lists the mode (Attributes), LastWriteTime, file size (Length), and the Name of the item.

Why we use $_ in PowerShell?

The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.

How do I select a directory in PowerShell?

You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).

How do I list only directories in PowerShell?

To get folder name only in PowerShell, use Get-ChildItem – Directory parameter and select Name property to list folder name only on PowerShell console.


1 Answers

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.

like image 105
manojlds Avatar answered Oct 06 '22 13:10

manojlds