无法使用Powershell中的Get-ChildItem -Exclude参数排除目录

时间:2013-11-07 17:34:25

标签: powershell powershell-v2.0

我正在使用Powershell v 2.0。并将文件和目录从一个位置复制到另一个位置。我使用字符串[]来过滤掉文件类型,还需要过滤掉被复制的目录。正在过滤掉正确的文件,但是,我尝试过滤obj的目录仍在被复制。

$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
        }
    }

我尝试了各种方法来过滤它,\obj*obj*\obj\但似乎没有任何效果。

感谢您的帮助。

3 个答案:

答案 0 :(得分:55)

-Exclude参数非常破碎。我建议您使用Where-Object (?{})过滤不需要的目录。例如:

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

P.S。:警示语 - 甚至不考虑在-Exclude本身使用Copy-Item

答案 1 :(得分:7)

我用它来列出根目录下的文件,但不包括目录

$files = gci 'C:\' -Recurse  | Where-Object{!($_.PSIsContainer)}

答案 2 :(得分:5)

Get-ChildItem -Path $SourcePath -File -Recurse | 
Where-Object { !($_.FullName).StartsWith($DestinationPath) }