【问题标题】:Get contents of subfolders containing a string in their name获取名称中包含字符串的子文件夹的内容
【发布时间】:2017-08-16 16:00:04
【问题描述】:

我想获取同一根文件夹的子文件夹中的所有文件,这些文件在子文件夹的名称中都包含相同的字符串(“foo”)。下面没有给我错误,也没有输出。我不知道我错过了什么。

Get-ChildItem $rootfolder | where {$_.Attributes -eq 'Directory' -and $_.BaseName -contains 'foo'}) | echo $file

最终,我不仅想呼应他们的名字,还想将每个文件移动到目标文件夹。

谢谢。

【问题讨论】:

    标签: powershell path directory move


    【解决方案1】:

    替换

    Get-ChildItem $rootfolder | where {$_.Attributes -match 'Directory' -and $_.basename -Match 'foo'}) | echo $file
    

    Get-ChildItem $rootfolder | where {($_.Attributes -eq 'Directory') -and ($_.basename -like '*foo*')} | Move-Item $targetPath
    

    您的要求:

    都包含相同的字符串(“foo”)

    您必须使用-like 比较运算符。同样对于完全匹配,我会使用-eq(区分大小写的版本是-ceq)而不是-match,因为它用于匹配子字符串和模式。

    工作流程: 获取目录中的所有文件,通过管道将其发送到您根据属性 Attributes 和 Basename 进行过滤的 Where-Object cmdlet。过滤完成后,将其发送到 cmdlet Move-Item。

    【讨论】:

    • 谢谢.. 但这会移动子文件夹和内容.. 我只想移动每个子文件夹的内容
    • Get-ChildItem $rootfolder -File -Recurse | where {$_.basename -like '*foo*'} | Move-Item $targetPath 试试这个。您必须首先获取所有文件(不包括文件夹),然后对其进行过滤。让我知道这是否有效,并用解释更新答案。
    【解决方案2】:

    使前两个变量适应您的环境。

    $rootfolder = 'C:\Test'
    $target = 'X:\path\to\whereever'
    Get-ChildItem $rootfolder -Filter '*foo*' | 
      Where {$_.PSiscontainer} | 
        ForEach-Object {
          "Processing folder: {0} " -f $_
         Move $_\*  -Destination $target
       }
    

    【讨论】:

      【解决方案3】:

      这是一个解决方案,包括将每个文件夹的子文件移动到新的目标文件夹:

      $RootFolder = '.'
      $TargetFolder = '.\Test'
      
      Get-ChildItem $RootFolder | Where-Object {$_.PSIsContainer -and $_.BaseName -match 'foo'} |
          ForEach-Object { Get-ChildItem $_.FullName |
          ForEach-Object { Move-Item $_.FullName $TargetFolder -WhatIf } }
      

      当您满意时删除-WhatIf,它正在做它应该做的事情。

      如果您(例如)想要排除文件夹的子目录,或者想要在这些路径的所有子文件夹中包含子项目,而不是文件夹本身,则可能需要修改 Get-ChildItem $_.FullName 部分。

      【讨论】:

        猜你喜欢
        • 2017-08-14
        • 2022-01-09
        • 1970-01-01
        • 2014-10-20
        • 2014-05-02
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多