获取名称中包含字符串的子文件夹的内容

Get contents of subfolders containing a string in their name

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

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

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

谢谢。

替换

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

您的要求:

that all contain the same string ("foo")

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

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

根据您的环境调整前两个变量。

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

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

$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 部分,但不是文件夹本身。