【问题标题】:powershell GCI recursively skipping folders and certain file typespowershell GCI递归跳过文件夹和某些文件类型
【发布时间】:2013-01-18 18:49:12
【问题描述】:

目前我正在使用这一行来收集某个路径(及以上)中的所有文件

$files = Get-ChildItem -Path $loc -Recurse | ? { !$_.PSIsContainer }

但是现在我一直要求生成此列表,同时排除(例如)所有“docx”和“xlsx”文件......以及名为“scripts”的文件夹及其内容

我想将这些文件扩展名和目录名从 txt 文件读入一个数组,然后简单地使用该数组。

速度也很重要,因为我将在这些文件上执行的功能需要足够长的时间,我不需要这个过程减慢我的脚本 10 完整(有点可以)

非常感谢您的任何意见

尝试失败:

gi -path H:\* -exclude $xfolders | gci -recurse -exclude $xfiles | where-object { -not $_.PSIsContainer }

我认为这可行,但仅在 H:\ 驱动器的根目录排除文件夹

【问题讨论】:

    标签: powershell directory file-extension get-childitem


    【解决方案1】:

    这样的?如果$loc 包含要忽略的文件夹名称之一,我只比较实际路径(来自$loc 的路径)。

    $loc = "C:\tools\scripts\myscripts\"
    $files = Get-ChildItem -Path $loc -Recurse -Exclude *.docx, *.xlsx | ? { !$_.PSIsContainer -and !($_.FullName.Replace($loc,"") -like "*scripts\*") }
    

    多个文件夹(这很难看):

    #Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
    $loc = "C:\tools\scripts\myscripts"
    $ignore = @("testfolder1","testfolder2");
    
    $files = Get-ChildItem -Path $loc -Recurse -Exclude *.docx, *.xlsx | ? { !$_.PSIsContainer } | % { $relative = $_.FullName.Replace($loc,""); $nomatch = $true; foreach ($folder in $ignore) { if($relative -like "*\$folder\*") { $nomatch = $false } }; if ($nomatch) { $_ } }
    

    【讨论】:

    • 那很漂亮......完美运行......我想提供多个文件夹名称和带有数组的文件扩展名......对于文件“-exclude $array”应该可以正常工作,但是我怎样才能为文件夹排除做到这一点?
    • 您将如何指定文件夹?全路径名(例如'c:\tools\scripts\myscripts\test\...')或只是一个随机文件夹名(例如'test')?
    • 用户通过文本文件提供,每行一个文件夹名......所以是的,例如排除所有名为“test”和“documents”的文件夹......不是完整路径
    • 现在更新答案。我认为有人可以简化它,但它似乎至少可以工作。
    • 哇...不是最优雅的,但它确实有效...我担心它的速度...打算试一试
    【解决方案2】:

    如果我理解了这个问题,那么您就走在了正确的道路上。要排除 *.docx 文件和 *.xlsx 文件,您需要将它们作为过滤字符串数组提供给 -exclude 参数。

    $files = Get-ChildItem -Path $loc -Recurse -Exclude @('*.docx','*.xlsx') | ? { !$_.PSIsContainer }
    

    【讨论】:

    • 适用于文件...但我需要排除文件夹及其内容
    【解决方案3】:

    我也在尝试这样做,Graimer 的回答没有奏效(也太复杂了),所以我想出了以下内容。

    $ignore = @("*testfolder1*","*testfolder2*");
    $directories = gci $loc -Exclude $ignore | ? { $_.PSIsContainer } | sort CreationTime -desc
    

    【讨论】:

      【解决方案4】:

      在 PowerShell 版本 3 中,我们可以告诉 Get-ChildItem 仅显示文件,如下所示:

      PS> $files = Get-ChildItem -File -Recurse -Path $loc 
      

      如果您只想收集某些文件名(例如 abc*.txt),您还可以使用过滤器:

      PS> $files = Get-ChildItem -File -Recurse -Path $loc -Filter abc*.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-20
        • 2013-07-28
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 2020-05-11
        相关资源
        最近更新 更多