【问题标题】:Unable to exclude directory using Get-ChildItem -Exclude parameter in Powershell无法在 Powershell 中使用 Get-ChildItem -Exclude 参数排除目录
【发布时间】:2013-11-19 12:00:53
【问题描述】:

我正在使用 Powershell v 2.0。并将文件和目录从一个位置复制到另一个位置。我正在使用 string[] 来过滤掉文件类型,并且还需要过滤掉被复制的目录。文件被正确过滤掉了,但是,我试图过滤的目录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\ 但似乎没有任何效果。

感谢您的帮助。

【问题讨论】:

标签: powershell powershell-2.0


【解决方案1】:

-Exclude 参数很糟糕。我建议您使用Where-Object (?{}) 过滤您不想使用的目录。例如:

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

P.S.:警告词 - 甚至不要考虑在 Copy-Item 本身上使用 -Exclude

【讨论】:

  • 谢谢!像魅力一样工作!
  • 如果您正在寻找 POSH 5.0 示例或处理多个排除项的方法,请查看以下答案:stackoverflow.com/a/35993562/615422
  • "$_.fullname -notmatch '//obj//' 在这里的作用是什么?对不起,我是 powershell 通配符的新手。
  • 支持“-Exclude 参数非常糟糕”,因为它是,而且您是第一个/唯一一个诊断出问题的人。谢谢。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    Get-ChildItem -Path $SourcePath -File -Recurse | 
    Where-Object { !($_.FullName).StartsWith($DestinationPath) } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      • 2017-03-15
      • 2013-02-24
      • 2017-08-28
      • 1970-01-01
      • 2013-06-16
      相关资源
      最近更新 更多