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

二次信任 提交于 2019-11-27 02:33:02

问题


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.


回答1:


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.




回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/19842754/unable-to-exclude-directory-using-get-childitem-exclude-parameter-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!