无法递归排除目录模式


30

我正在尝试递归获取文件夹的子项。但是,该文件夹包含噪波文件和文件夹(实际上,这是Visual Studio项目文件夹)。

这是我所拥有的:

$root = Get-Item C:\Projects\MyProject

$allItems =  Get-ChildItem $root -Recurse -exclude "**\pkgobj\*"

但是,$allItems仍然包含与路径匹配的文件和文件夹。

我做错了什么?

更精确地说,我想同时获取文件夹和文件,但不获取指定的文件夹及其任何后代。

我也尝试过:

foreach($item in $allItems){
    if($item.FullName -notmatch "pkgobj") {
        Write-Host -ForegroundColor Green $item.FullName.Replace($root,'')

    }
}

但是没有更多的成功

Answers:


44

花了我一点时间来理解这个问题。这是一个棘手的问题。

-exclude仅适用于项目的基本名称(即myfile.txt),而不适用于所需的全名
(即C:\pkgobj\myfile.txt)。因此,您不能在此处使用排除

但是有一种解决方法是使用Fullname-notlike

$root = "C:\Projects\MyProject"
$allitems = Get-ChildItem $root -Recurse | Where {$_.FullName -notlike "*\pkgobj\*"} 

1
但是,如果由于性能而想排除大型目录(例如node_modules),这将无济于事,因为它仍将递归检查所有内容并随后进行过滤。
Pluc

那这个呢 ?Get-ChildItem-排除exclude_dir | foreach {Get-ChildItem -Path $ _ -Include * .include -Recurse -Exclude * .excludefile | foreach {echo $ _}}
NN_
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.